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">

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

6 Comments

do we need model for submit button?
I don't see the rest of the code but the inputs should all look kinda like this <input type="text" name="userName" ng-model="user.name" required> and for my buttons I do like just a basic ng-model of like submit button just so I can track those events. See 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.
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.
Are you setting it inside the controller, compile or link function?
inside the link function. edited the code in question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.