jean-Philippe jean-Philippe - 3 months ago 8
AngularJS Question

Can i set a html input field invalid regarding an angular model variable value?

I have a html form with an email input. I already handle min length - max length - email pattern and required errors with ng-messages-exp;
Now i want this field to be invalid if a variable of the $scope is set to true. (I will ask the server if the mail is taken or not.)

<md-input-container class="md-block">
<label class="inputLabel">Email</label>
<input required="" type="email" name="accountEmail" ng-model="signup.account.email" minlength="10" maxlength="100" ng-pattern="/^.+@.+\..+$/">

<div ng-messages="signupForm.accountEmail.$error" role="alert">
<div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
Your email must be between 10 and 100 characters long and look like an e-mail address.
</div>
</div>
</md-input-container>


Can someone know how to set an input invalid regarding a $scope var?

Thank you!

Answer

add a name attribute to the <form> and <input>, and then in the controller its possible to do $scope.formName.inputName.$setValidity(errorKey, isValid).

Then, its possible to display errors with something like ng-show="formName.inputName.$error.errorkey"

according to http://docs.angularjs.org/api/ng.directive:form If name attribute is specified, the form controller is published onto the current scope under this name.