Michael Roeper
Michael Roeper

Reputation: 21

Problems with angular validation in directive

I am fighting with the validation in an angular directive without success.

The form.name.$error object seems to be undefined, when I submit the name property to the directive template. If i use a fixed name-attribute inside the template, the $error object is fine, but of course identical for all elements.

The html is:

 <form name="form" novalidate>

<p>
  <testvalidation2 name="field1" form="form"  field="testfield4" required="true"> 
  </testvalidation2>
</p>
</form>

The directive looks like this:

app.directive('testvalidation2', function(){
return {
restrict: 'E',
scope: {
  ngModel: '=',
  newfield: '=field',
  required: '=required',
  form: '='
},
templateUrl: 'template2.html',
link: function(scope, element, attr){
 scope.pattern = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
 scope.name = attr.name;
}

} // return });`

and finally the template:

<div>
<input  name="{{name}}" type="text" ng-model="newfield" ng-required="required" ng-pattern="pattern"> {{FIELD}}</input>
<span ng-show="form.name.$error.required">Required</span>
<span ng-show="form.name.$error.pattern"> Invalid </span>
<p>Output {{form.name.$error | json}}</p>
</div>

I have created a plunker for my Angular Validation Problem and would be happy, if someone would help me to win the fight.

Michael

Upvotes: 1

Views: 226

Answers (1)

Chandermani
Chandermani

Reputation: 42669

I don't have a fix for this but I can tell you what the problem is.

  • Firstly in your html form="form" should have name of the form form="form2".
  • Secondly Since you are creating a new scope in the directive, the scope created is a isolated scope which does not inherit from parent, which means that the the template input control that you add would not get added to the parent scope form2.

The only way out currently i can think of is to not use isolated scope.

Upvotes: 1

Related Questions