I'm hoping this isn't a duplicate - plenty of similar questions about but I can't find an answer that works.
I have an Angular directive, thus:
app.directive('emailInput', function(){ return { restrict: 'E', templateUrl: 'template.html', link: function(scope, elem, attrs, ctrl){ elem.bind('keyup', function(){ // TODO - what? }) } } }
and in the template html:
<input type="email" required ng-model="emailAddress" />
Without knowing the name of the form, inside the link
function, I want to know the value of the emailAddress.$valid
property - how can I get this?
The form instance can optionally be published into the scope using the name attribute. So to check form validity, you can check value of $scope. yourformname. $valid property of scope.
The $setValidity() function is a built-in AngularJS function that is used to assign a key/value combination that can be used to check the validity of a specific model value. The key in this case is “unique” and the value is either true or false.
$dirty means the user has changed the input value, $invalid means the address itself is invalid. Therefore the error is only shown if the user has actively changed the input value to either an empty or invalid value.
You could also use ng-hide="somefield. length" instead of ng-show="!
You can require the formController which would give you access to all of the inputs registered to the form
app.directive('emailInput', function(){ return { require: '^form', // We look for it on a parent, since it will be defined somewhere higher on the DOM. restrict: 'E', templateUrl: 'template.html', link: function(scope, elem, attrs, ctrl){ elem.bind('keyup', function(){ ctrl.emailAddress.$valid //check validity }) } } }
Remember that Angular keeps track of input elements by name. So you have to give your input a name attribute
<input type="email" required ng-model="emailAddress" name="emailAddress" />
I would also recommend possibly just passing all of this through a directive attribute. You probably don't want to hard code the field names. So you could just have an attribute that takes the validity
inputIsValid='formName.emailAddress.$valid'
And evaluate (or $watch it) in your directive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With