FERNANDO ORTIZ FERNANDO ORTIZ - 1 month ago 6
AngularJS Question

change color to the same element angular

Hi I have the following problem, when I click on an item changes color to all elements but I need to change only the color that I clicked:

<div ng-app="myApp" ng-controller="myCtrl as model">
<button ng-click="model.addComparative()"> add
</button>
<div ng-repeat="item in model.items track by $index">
<button ng-model="model.myModel" ng-click="model.changeColor()" ng-class="{'red':model.myModel==true}">click me</button>
</div>

angular
.module("myApp",[])
.controller('myCtrl', function($scope){
var model=this;
model.myModel=false;
model.items=[];
model.newItems = '';
model.addComparative = function(){
model.items.push(model.newItems)
}
model.changeColor = function(){
model.myModel = true;
}
})


and the codepen: http://codepen.io/fernandooj/pen/rrdZWE

Answer

Try using the current index of each item:

html file

<button ng-model="model.myModel" ng-click="model.changeColor($index)" ng-class="{'red':model.items[$index].selected==true}">click me</button>

js file

model.addComparative = function(){
    model.items.push({}); // What you append needs to be an object.
}
model.changeColor = function(index){
    model.items[index].selected = true;
};
Comments