当我在ng-repeat中单击ng单击时,如何更新ng类?
.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>
脚本
$scope.changeColor = function(c){
if(c){
$scope.color = true;
}else{
$scope.color = false;
}
}
我已经试过了,但它不起作用。
更新
我只想更改单击的按钮的颜色。
代码的问题在于,对于集合中的所有元素,您使用相同的标志,即 $scope.color
.当此标志更改时,它会更改所有按钮的颜色。
为了缓解这种情况,一种方法是拥有一个包含值的数组 true
和 false
在指定的索引处,并使用该数组来决定模板中的类分配。
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>
您应该维护元素上的color
属性,而不是使用全局(单个(color
属性来实现样式效果。我会说传递整个实体x
来更改颜色方法并在用户单击它时切换color
属性。
.HTML
<div ng-repeat="x in y">
<button ng-class="{'red':color,'blue':!color}" ng-click="changeColor(x)">
Change Color
</button>
</div>
或
<div ng-repeat="x in y">
<button ng-class="color ? 'red: 'blue'" ng-click="changeColor(x)">
Change Color
</button>
</div>
法典
$scope.changeColor = function(c){
c.color = !c.color;
}