Samih
Samih

Reputation: 1098

Angular ng-class not updating after ng-change is fired

EDIT: It seems my issue is more complex than the simple typo in the code below. I have 3rd party components interacting and raising change events on the inputs which angular is picking up when I don't want it to. The problem is somewhere in there. I will try to find a simple fiddle and update the question if I manage it.

I have a pair of inputs, which have an ng-model and share an ng-change function. The ng-change sets a boolean value in the controller which is supposed to update the class(es) on the inputs through an ng-class directive. However the first of the two inputs never seems to get any updates to it's class. Here is a simplified version:

View:

<div ng-controller='TestCtrl'>
    <input type="text" ng-class="{ 'invalid': firstInvalid }" ng-model="firstValue" ng-change="doOnChange()"></input>      
    <input type="text" ng-class="{ 'invalid': secondInvalid }" ng-model="secondValue" ng-change="doOnChange()"></input>
</div>

Controller:

function TestCtrl($scope) {
  $scope.firstInvalid = false;
  $scope.secondInvalid = false;
  $scope.firstValue = '';
  $scope.secondValue = '';

  $scope.doOnChange = function () {
      console.log('change fired');
      $scope.firstInValid = !$scope.firstInvalid;
      $scope.secondInvalid = !$scope.secondInvalid;
  };

};

Codepen: http://codepen.io/Samih/pen/ZGXQPJ

Notice how typing in either input, the second input updates with the class just as I would expect, however the first never gets the 'invalid' class.

Thanks in advance for your help.

Upvotes: 1

Views: 1203

Answers (2)

Vikash
Vikash

Reputation: 1141

It seems to work for me : Just edited 'firstInvalid'.

View:

<div ng-controller='TestCtrl'>
    <input type="text" ng-class="{ 'invalid': firstInvalid }" ng-model="firstValue" ng-change="doOnChange()"></input>      
    <input type="text" ng-class="{ 'invalid': secondInvalid }" ng-model="secondValue" ng-change="doOnChange()"></input>
</div>

Controller:

function TestCtrl($scope) {
  $scope.firstInvalid = false;
  $scope.secondInvalid = false;
  $scope.firstValue = '';
  $scope.secondValue = '';

  $scope.doOnChange = function () {
      console.log('change fired');
      $scope.firstInvalid = !$scope.firstInvalid;
      $scope.secondInvalid = !$scope.secondInvalid;
  };

};

Codepen: http://codepen.io/vikashverma/pen/BNwKmQ

Upvotes: 0

Todd
Todd

Reputation: 1674

Check your code for typos:

This line

 $scope.firstInValid = !$scope.firstInvalid;

should be

 $scope.firstInvalid = !$scope.firstInvalid;

It should be $scope.firstInvalid, not $scope.firstInValid.

Upvotes: 1

Related Questions