我在点击时有一个演示,它改变了课程的价值,但我无法弄清楚如何单独更改它们。
以下是演示以获得更好的解释:http://jsfiddle.net/pWG2S/1260/
我可以使用class2,class3等向js添加类似的代码行,但问题是这个类会重复很多次。如果您对如何解决这个问题有任何想法,那就太棒了。提前谢谢
$scope.changeClass = function(){
if ($scope.class === "rotated")
$scope.class = "rotated2";
else
$scope.class = "rotated";
};
答案 0 :(得分:1)
只需将class
更改为数组,然后传递每个索引:
$scope.changeClass = function(i){
if ($scope.class[i] === "red")
$scope.class[i] = "blue";
else
$scope.class[i] = "red";
};
答案 1 :(得分:1)
HTML:
<body ng-app="ap" ng-controller="con">
<div ng-class="class">{{class}}</div>
<button id="button1" ng-click="changeClass($event)">Change Class</button>
<div ng-class="class1">{{class1}}</div>
<button id="button2" ng-click="changeClass($event)">Change Class</button>
</body>
JS:
var app = angular.module("ap",[]);
app.controller("con",function($scope){
$scope.class = "red";
$scope.class1 = "red";
$scope.changeClass = function(event){
console.log(event.currentTarget.id);
if(event.currentTarget.id === "button1")
if ($scope.class === "red")
$scope.class = "blue";
else
$scope.class = "red";
else if(event.currentTarget.id === "button2")
if ($scope.class1 === "red")
$scope.class1 = "blue";
else
$scope.class1 = "red";
};
});
我应该重新编写代码。不过,我最初的想法是,您需要将$event
与ng-click
一起传入,并向按钮提供ID,以便通过event.currentTarget.id
Nghi Nguyen 的小提琴使用指令更有意义,因为你的同一组元素是两次。将它们封装在指令中。这样您甚至不必使用 $ event 来确定按钮的ID,控制器只会处理特定指令的changeClass。
<强> EDIT1:强>
var app = angular.module("ap",[]);
app.controller("con",function($scope){
$scope.class = "red"; // default class
$scope.changeClass = function($event){
if ($($event.target).prev().hasClass('red')) {
$($event.target).prev().removeClass('red').addClass('blue');
} else {
$($event.target).prev().removeClass('blue').addClass('red');
}
};
});
HTML:
<body ng-app="ap" ng-controller="con">
<div ng-class="class">{{class}}</div>
<button ng-click="changeClass($event)">Change Class</button>
<div ng-class="class">{{class}}</div>
<button ng-click="changeClass($event)" >Change Class</button>
</body>
答案 2 :(得分:0)
让我们考虑每个部分的make指令:
<div ng-class="class">{{class}}</div>
<button ng-click="changeClass()">Change Class</button>
然后您可以控制每个指令中的范围,以便以后扩展。
答案 3 :(得分:0)
这个怎么样?
<强>控制器强>
var app = angular.module("ap",[]);
app.controller("con",function($scope){
$scope.klasses = ["red", "blue", "yellow"];
$scope.klassIndex = 0;
$scope.changeClass = function(){
var newKlassIndex = ($scope.klassIndex+1)%$scope.klasses.length;
$scope.klassIndex = newKlassIndex;
};
});
查看强>
<body ng-app="ap" ng-controller="con">
<div ng-repeat="klass in klasses">
<div ng-class="klasses[klassIndex]">{{klasses[klassIndex]}}</div>
<button ng-click="changeClass()">Change Class</button>
</div>
</body>
这样就可以使用新的相应CSS规则将新类添加到 $ scope.klasses 。