当您点击其中一个addOn时,在ng-class =" {{sectionClass}}"中,我想为该元素添加一个类。
有没有更好的方法来实现这一目标?
我的方式不起作用,我不确定代码有什么问题。
$scope.addOns = [
{
name: "Cover options"
},
{
name: "Stamping"
}
];
$scope.sectionClass = function(addOn){
if (addOn.name == "Cover options")
return("covers");
else if (addOn.name == "Stamping")
return("stamping");
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="section-content" ng-class="{{sectionClass}}">
<div class="add-on-type" ng-click="sectionClass(addOns)" ng-repeat="addOn in addOns">
<span>{{addOn.name}}</span>
</div>
</div>
&#13;
答案 0 :(得分:0)
你错过了几件事
从addon
ng-repeat
函数传递ng-click
个对象,如ng-click="sectionClass(addOn)"
不要从方法返回字符串,而是设置一个范围变量,如customClass
&amp;在ng-class
指令
<强> HTML 强>
<div ng-app="myApp" ng-controller="MyCtrl" >
<div class="section-content" ng-class="{{customClass}}">
<div class="add-on-type" ng-click="sectionClass(addOn)" ng-repeat="addOn in addOns"> <span>{{addOn.name}}</span>
</div>
</div>
</div>
<强>控制器强>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.addOns = [
{
name: "Cover options"
}, {
name: "Stamping"
}];
$scope.sectionClass = function (addOn) {
if (addOn.name == "Cover options")
$scope.customClass="covers"
else if (addOn.name == "Stamping")
$scope.customClass="stamping"
}
});
希望这可以帮到你。感谢。