Reputation: 89
i'm trying to do basic validation of the form fields in angular. It works properly when i inline the input field(s) with the form, however when I'm trying to use directives for inserting the input form field, the validation does not work as expected.
here is the JSbin showing the problem. I would appreciate some help thanks!
http://jsbin.com/sufotecenovi/2/edit
Upvotes: 1
Views: 1975
Reputation: 11
Click Here you can use this code.
function MyCtrl($scope) {
$scope.formFields = [
{
name: 'firstName',
type: 'text'
},
{
name: 'email',
type: 'email'
}
];
}
myApp.directive("dynamicName",function($compile){
return {
restrict:"A",
terminal:true,
priority:1000,
link:function(scope,element,attrs){
element.attr('name', scope.$eval(attrs.dynamicName));
element.removeAttr("dynamic-name");
$compile(element)(scope);
}
};
});
<div ng-controller="MyCtrl">
<form name="myForm">
<p ng-repeat="field in formFields">
<input
dynamic-name="field.name"
type="{{ field.type }}"
placeholder="{{ field.name }}"
ng-model="field.value"
required
>
</p>
<code class="ie">
myForm.firstName.$valid = {{ myForm.firstName.$valid }}
</code>
<code class="ie">
myForm.email.$valid = {{ myForm.email.$valid }}
</code>
<code class="ie">
myForm.$valid = {{ myForm.$valid }}
</code>
<hr>
</form>
</div>
Upvotes: 1
Reputation: 52847
Angular uses the 'name' attribute to create the $scope variables used for validation.
For example, if you have an input field with a 'required' attribute:
<form name="myform">
<input name="firstname" ng-model="firstname" type="text" required/>
</form>
Then to access the validation properties on $scope, you would do:
var validationFailed = $scope.myform.firstname.$error.required;
Where $error is an object that has 'required' as a Boolean property.
In the 'required' directive, you would see something like this:
if(attrs.value == ''){
ngModel.$setValidity('required', true); // failed validation
} else {
ngModel.$setValidity('required', false); // passed validation
}
You can pass any string to $setValidity, and it will set the $error property for you. For example, if you did:
$setValidity('test', true)
Then there would be an $error property named 'test' and it would be set to true. You can then access the property like this:
$scope.myform.firstname.$error.test
Other validation properties that are available are:
$scope.myform.firstname.$valid
$scope.myform.firstname.$invalid
$scope.myform.firstname.$pristine
$scope.myform.$valid
$scope.myform.$invalid
$scope.myform.$pristine
Hope this helps to answer your question.
Upvotes: 1