Reputation: 2325
I have a dynamic form and I want to solve the input errors. The input name is created dynamicaly, 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 (which is 'name'). Any suggestion?
HTML
<div ng-app='app' ng-controller='Main'>
<form name='mailForm' ng-submit='submit(mailForm.$valid,form);$event.preventDefault();' novalidate>
<ng-form name='innerForm'>
<p>
Name:
<input type='text' name='{{inputName}}' ng-model='form.name' required>
<span ng-if="innerForm.inputName.$invalid && innerForm.inputName.$touched">required</span>
</p>
</ng-form>
<br><br>
<input type="submit" value='Submit' ng-disabled="mailForm.$invalid" />
</form>
</div>
Javascript
angular.module('app',[])
.controller('Main', function($scope){
$scope.inputName = 'name';
$scope.submit = function(isValid, form){
console.log('isValid',isValid);
console.log('form',form);
};
});
Upvotes: 0
Views: 67
Reputation: 519
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
EDIT
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
Upvotes: 1
Reputation: 9873
Change
<input type='text' name='{{inputName}}' ng-model='form.name' required>
to
<input type='text' name='inputName' ng-model='form.name' required>
Differences: {{inputName}}
to inputName
The name attribute must be plain text. If you want to use the brackets, then set that inputName
scope variable to 'inputName' in your controller, since you are trying to access it as innerForm.inputName.$invalid
. The inputName
property much match the string in the name field on the form.
Upvotes: 0