Search code examples
cssangularjsng-class

Why doesn't ng-class evaluate unless the input is modified manually?


I've got an textarea input which is bound to a model. I also have a select which has an ng-change which fires a scope function. When one changes the select, the model is changed. The function on ng-class is comparing the original value of the model with the current value. The class which is added is used to color the background of the textarea such that when the the current value == original value the background is white. But there is something odd at play here.

Case 1:

  1. Run the fiddle
  2. Select ‘2017-10-12’ in the select box. The select background goes green (as intended) but the textarea background remains white.

Case 2:

  1. Run the fiddle
  2. Click into the textarea and change the value. The textarea goes green as intended. Typing the original value causes the textarea to go white as intended.
  3. Choose ‘2017-10-12’ in the select box. The select background goes green AND the textarea goes green as well. (as intended)
  4. Choose ‘2017-11-01’ in the select box. The select background goes white AND the textarea goes white as well. (as intended)

Why doesn't case #1 work?

See the jsFiddle


Solution

  • It's about the dirty checking and your CSS around it:

    .form-control.ng-dirty.ng-valid, select.ng-dirty.ng-valid {
      background-color: $formDirtyValid;
    }
    
    .form-control.ng-dirty.ng-valid.nochange, select.ng-dirty.ng-valid.nochange {
      background-color: $formBack ;
    }
    

    Input elements will only have a class "ng-dirty" on it after you changed the input.

    you could fix it by removing the ".ng-dirty" class selector from all css selectors, like so:

    .form-control.ng-valid, select.ng-valid {
      background-color: $formDirtyValid;
    }
    
    .form-control.ng-valid.nochange, select.ng-valid.nochange {
      background-color: $formBack ;
    }
    

    https://jsfiddle.net/evmt2c56/15/