假设你有一个在ul中呈现的数组,每个元素都有一个li,控制器上有一个名为selectedIndex的属性。在AngularJS中,用索引selectedIndex向li中添加类的最好方法是什么?
我目前复制(手工)li代码,并将类添加到li标记之一,并使用ng-show和ng-hide只显示每个索引一个li。
假设你有一个在ul中呈现的数组,每个元素都有一个li,控制器上有一个名为selectedIndex的属性。在AngularJS中,用索引selectedIndex向li中添加类的最好方法是什么?
我目前复制(手工)li代码,并将类添加到li标记之一,并使用ng-show和ng-hide只显示每个索引一个li。
当前回答
下面是另一个在ng-class不能使用时工作得很好的选项(例如在样式化SVG时):
ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}"
(我认为你需要使用最新的不稳定Angular才能使用ng-attr-,我目前使用的是1.1.4)
其他回答
三元运算符刚刚在1.1.5中被添加到角解析器中。
所以最简单的方法就是:
ng:class="($index==selectedIndex)? 'selected' : ''"
这是我在工作中多次有条件的判断:
<li ng-repeat='eOption in exam.examOptions' ng-class="exam.examTitle.ANSWER_COM==exam.examTitle.RIGHT_ANSWER?(eOption.eoSequence==exam.examTitle.ANSWER_COM?'right':''):eOption.eoSequence==exam.examTitle.ANSWER_COM?'wrong':eOption.eoSequence==exam.examTitle.RIGHT_ANSWER?'right':''">
<strong>{{eOption.eoSequence}}</strong> |
<span ng-bind-html="eOption.eoName | to_trusted">2020 元</span>
</li>
我是Angular的新手,但我发现这个可以解决我的问题:
<i class="icon-download" ng-click="showDetails = ! showDetails" ng-class="{'icon-upload': showDetails}"></i>
这将有条件地应用一个基于var的类。 它以默认的icon-download开始,使用ng-class,我检查showDetails的状态,如果为真/假,并应用class icon-upload。它工作得很好。
希望能有所帮助。
这里有一个更简单的解决方案:
function MyControl($scope){ $scope.values = ["a","b","c","d","e","f"]; $scope.selectedIndex = -1; $scope.toggleSelect = function(ind){ if( ind === $scope.selectedIndex ){ $scope.selectedIndex = -1; } else{ $scope.selectedIndex = ind; } } $scope.getClass = function(ind){ if( ind === $scope.selectedIndex ){ return "selected"; } else{ return ""; } } $scope.getButtonLabel = function(ind){ if( ind === $scope.selectedIndex ){ return "Deselect"; } else{ return "Select"; } } } .selected { color:red; } <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script> <div ng-app ng-controller="MyControl"> <ul> <li ng-class="getClass($index)" ng-repeat="value in values" >{{value}} <button ng-click="toggleSelect($index)">{{getButtonLabel($index)}}</button></li> </ul> <p>Selected: {{selectedIndex}}</p> </div>
我建议你用一个返回true或false的函数来检查控制器中的条件。
<div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>
在你的控制器中检查情况
$scope.getTodayForHighLight = function(today, date){
return (today == date);
}