0

I needed to add input validation from the directive.

I tried

return{
    restrict: 'A',
    link: function(scope, elem, attrs){
        attrs.$set('required', 'required');     
    }
}

I can see this attribute on the dom but form is not validating it. I am validating the form using this submit shown below.

<input type="submit" value="submit" ng-disabled="myForm.$invalid">
Abel D
  • 1,040
  • 1
  • 18
  • 30

2 Answers2

1

The main reason your code doesn't work is because you are not using $compile again on the element, once you have added the attribute.

Angular needs to re-parse the element and run the 'ng-required' directive after you have added it as an attribute, otherwise angular doesn't know about it because the DOM has already been rendered.

The other thing is that you can do so during the compile phase rather than the link phase as I can see that you are not using anything from the scope.

So here is what you can do:

angular.module('app')
.directive('customDirective', function ($compile) {
return {
  restrict: 'A',
  replace: false, 
  terminal: true,
  priority: 1000,
  compile: function compile(element, attrs) {
    element.attr('required', 'required');
    element.removeAttr("custom-directive"); //remove the attribute to avoid indefinite loop
    $compile(element)(scope);
  }
};
});

You can read more in this SO answer

Community
  • 1
  • 1
Michele Ricciardi
  • 2,107
  • 14
  • 17
0

If you don't have a model assigned to the input validation kinda gets wonky. I would suggest adding a model and rereading the following info.

https://docs.angularjs.org/api/ng/directive/input

James
  • 1,514
  • 12
  • 30
  • do we need model for submit button? – Abel D Jul 22 '15 at 18:51
  • I don't see the rest of the code but the inputs should all look kinda like this and for my buttons I do like just a basic ng-model of like submit button just so I can track those events. See https://docs.angularjs.org/guide/forms for an decent example of form validation. Also weird markup that might end your form or controller early can also be to blame because it might not be linking the submit to the form you want it to. – James Jul 22 '15 at 18:59
  • yes James I already have my models set. I am setting this validation from inside custom directive. I think i need somehow to compile it to get the effect. – Abel D Jul 22 '15 at 19:03
  • Are you setting it inside the controller, compile or link function? – James Jul 22 '15 at 19:37
  • inside the link function. edited the code in question. – Abel D Jul 22 '15 at 19:40
  • As the other commented stated if you aren't compiling the code after updating your changes are never really happening. Hope this helped. – James Jul 22 '15 at 19:55