您好我有以下问题,当我点击一个项目更改所有元素的颜色但我只需要更改我点击的颜色:
<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;
}
})
答案 0 :(得分:1)
尝试使用每个项目的当前索引:
html文件
<button ng-model="model.myModel" ng-click="model.changeColor(item)" ng-class="{'red':item.selected==true}">click me</button>
js文件
model.addComparative = function(){
model.items.push({}); // What you append needs to be an object.
}
model.changeColor = function(item){
item.selected = true;
};
答案 1 :(得分:0)
只需使用
<button ng-model="model.myModel"
ng-click="this.item.red=true"
ng-class="{'red':this.item.red}">click me</button>
ng-repeat 的$ index可能因摘要周期而异(如果没有订购商品),因此不可靠
在每个&#34; ADD&#34;上添加3个按钮。单击并使用JS onclick :
<div ng-app="myApp" ng-controller="myCtrl as model" ng-init="range=[0, 1, 2]">
<button ng-click="model.addComparative()"> add </button>
<div ng-repeat="item in model.items track by $index+3">
<button ng-repeat="i in range"
ng-model="model.myModel1"
onclick="this.style.background = 'red'">click me</button>
</div>
</div>
另请注意,您的所有按钮都具有相同的 ngModel ,可能不需要