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

angularjs

Solution

There are two good ways to approach this problem:

1. Use the built-in `ng-dirty` class that Angular puts on the element.

When you change an input managed by Angular, it adds some CSS classes to the input for various states. These include:

- `ng-pristine` - the input has not been modified

- `ng-dirty` - the input has been modified

So, if you can modify your CSS to be based off the `.ng-dirty` class, you're good to go.

2. Use a `form` directive with the `$dirty` flag.

When you use a `form` element, Angular assigns a `FormController` instance on the scope with the same name as the `name` attribute on the form; each input inside the form gets attached to that FormController instance as a property, again with the same name as the `name` attribute on the input. For example,

<form name="myForm">
  <input type="text" name="myInput">
</form>

gives you

$scope.myForm.myInput

Each input property has some of its own properties on it, including `$pristine` and `$dirty`; these work just like the CSS classes listed above. Thus, you can check for the `$dirty` flag on the input and use `ng-class` to conditionally apply a class to the element. An 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 a working example here: http://jsfiddle.net/BinaryMuse/BDB5b/

Problem

I coded the following in my form: ``` <td><input type="text" ng-model="row.title" /></td> ``` When I look at my DOM with Chrome developer tools I see the following: ``` <input type="text" ng-model="row.title" class="ng-pristine ng-valid"> ``` How can I make it so that when there is a change made to the input that the input has a class added to it?

Original source