Update ng-class in ng-repeat using ng-click

How can I update the ng-class when I click the ng-click in ng-repeat?

HTML

<div ng-repeat="x in y">
  <button ng-class="{'red':color==true,'blue':color==false}" ng-click="changeColor(x.color)">
    Change Color
  </button>
</div>

Script

$scope.changeColor = function(c){
  if(c){
    $scope.color = true;
  }else{
    $scope.color = false;
  }
}

I already tried this but it doesnt work.

UPDATE

I want to change only the color of the button clicked.

Upvotes: 0

Views: 78

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You should maintain color property on element rather than using global (single) color property for styling effect. I'd say pass whole entity x to change color method and toggle color property when user clicks on it.

HTML

<div ng-repeat="x in y">
  <button ng-class="{'red':color,'blue':!color}" ng-click="changeColor(x)">
    Change Color
  </button>
</div>

OR

<div ng-repeat="x in y">
  <button ng-class="color ? 'red: 'blue'" ng-click="changeColor(x)">
    Change Color
  </button>
</div>

Code

$scope.changeColor = function(c){
   c.color = !c.color;
}

Upvotes: 1

31piy
31piy

Reputation: 23859

The problem with your code is that for all the elements in the collection, you're using the same flag, i.e. $scope.color. When this flag changes, it changes all the buttons' color.

To mitigate that, one way is to have an array which contains the value true and false at the specified indices and use that array to decide the class assignment in the template.

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {

  $scope.y = [{
    color: 'r'
  }, {
    color: ''
  }];
  
  $scope.classes = [];

  $scope.changeColor = function(c, i) {
    if (c) {
      $scope.classes[i] = true;
    } else {
      $scope.classes[i] = false;
    }
  }

});
.red {
  color: red;
}

.blue {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="x in y track by $index">
    <button ng-class="{'red':classes[$index],'blue':classes[$index] !== undefined && !classes[$index]}" ng-click="changeColor(x.color, $index)">
    Change Color
  </button>
  </div>
</div>

Upvotes: 1

Related Questions