Reputation: 275
I have the following HTML element:
<input type="text" ng-model="form.artist" ng-class="form.artist.$invalid ? 'error' : ''" required ng-minlength="4">
But it does not work when I have invalid input "form.artist"
Upvotes: 1
Views: 6380
Reputation: 13997
You have to put a name
attribute to your input
, then your $invalid
flag comes of [formName].[inputName].$invalid
:
<form name="myForm">
<input type="text" name="artist" required
ng-minlength="4"
ng-model="form.artist"
ng-class="myForm.artist.$invalid ? 'error' : ''" />
<!-- or ng-class="{error:myForm.artist.$invalid}" -->
</form>
See this jsfiddle
See also the documentation of angular:
Similarly, an input control that has the ngModel directive holds an instance of NgModelController. Such a control instance can be published as a property of the form instance using the name attribute on the input control. The name attribute specifies the name of the property on the form instance.
Upvotes: 0
Reputation: 77
<form name="demoForm">
<input type="text" name="demoForm.artist" ng-model="form.artist" ng-class="{'yourclassname': demoForm.artist.$invalid && demoForm.artist.$dirty}">
</form>
Upvotes: 3
Reputation: 5711
Yes, you can use ng-class
attribute another way:
<input type="text" ng-model="form.artist" ng-class="{'error': form.artist.$invalid}">
Upvotes: 0
Reputation: 186
Use this
<div ng-class="{'class-name': 'condition'(boolean)}" </div>
In your case
<input type="text" ng-model="form.artist" ng-class="{'class-name':'form.artist.$invalid}">
Upvotes: 0