How can I add a class to an input if the input is changed with AngularJS? -


i coded following in form:

<td><input type="text" ng-model="row.title" /></td> 

when @ dom chrome developer tools see following:

<input type="text" ng-model="row.title" class="ng-pristine ng-valid"> 

how can make when there change made input input has class added it?

there 2 ways approach problem:

1. use built-in ng-dirty class angular puts on element.

when change input managed angular, adds css classes input various states. these include:

  • ng-pristine - input has not been modified
  • ng-dirty - input has been modified

so, if can modify css based off .ng-dirty class, you're go.

2. use form directive $dirty flag.

when use form element, angular assigns formcontroller instance on scope same name name attribute on form; each input inside form gets attached formcontroller instance property, again same name name attribute on input. example,

<form name="myform">   <input type="text" name="myinput"> </form> 

gives you

$scope.myform.myinput 

each input property has of own properties on it, including $pristine , $dirty; these work css classes listed above. thus, can check $dirty flag on input , use ng-class conditionally apply class element. example:

<div ng-controller="maincontroller">   <form name="myform">     <input name="myinput" ng-model="model" ng-maxlength="3"       ng-class="{changed: myform.myinput.$dirty}">   </form> </div> 

you can find working example here: http://jsfiddle.net/binarymuse/bdb5b/


Comments