webenergized webenergized - 5 months ago 25
AngularJS Question

How to treat error input in a dynamical angular form?

I have a dynamic form and I want to solve the input errors. The input name is created dynamical, but I can't access it in in the error span. I assume the angular double curly brackets executes / renders slower then the ngIf directive ? maybe that's why I don't have access to the innerForm.inputName (wich is 'name') ... Any suggestion ?

Live code


<div ng-app='app' ng-controller='Main'>

<form name='mailForm' ng-submit='submit(mailForm.$valid,form);$event.preventDefault();' novalidate>
<ng-form name='innerForm'>
<input type='text' name='{{inputName}}' ng-model='form.name' required>

<span ng-if="innerForm.inputName.$invalid && innerForm.inputName.$touched">required</span>

<input type="submit" value='Submit' ng-disabled="mailForm.$invalid" />


.controller('Main', function($scope){
$scope.inputName = 'name';

$scope.submit = function(isValid, form){


Answer EDIT

Since value is changing dynamically and you never know what will be the inputName value, you still can access the scope object via selecting by key, so the span error line should go like this:

<span ng-if="innerForm[inputName].$invalid && innerForm[inputName].$touched">required</span>

Since you use scope value in input name='{{inputName}}'

And in ng-if you try to read from innerForm.inputName

So in your controller you should set $scope.inputName = 'inputName';

Else when having $scope.inputName = 'name'; you will read the value of name in innerFrom


Also consider that you have disabled the submit button, when the form in invalid, so yeah, it wont let you submit until the you fill the form and it becomes valid