假设你有一个在ul中呈现的数组,每个元素都有一个li,控制器上有一个名为selectedIndex的属性。在AngularJS中,用索引selectedIndex向li中添加类的最好方法是什么?

我目前复制(手工)li代码,并将类添加到li标记之一,并使用ng-show和ng-hide只显示每个索引一个li。


当前回答

我要补充一点,因为有些答案似乎已经过时了。我是这样做的:

<class="ng-class:isSelected">

其中'isSelected'是定义在作用域角控制器中的javascript变量。 为了更具体地解决你的问题,下面是你如何用它生成一个列表:

超文本标记语言

<div ng-controller="ListCtrl">  
    <li class="ng-class:item.isSelected" ng-repeat="item in list">   
       {{item.name}}
    </li>  
</div>

JS

function ListCtrl($scope) {    
    $scope.list = [  
        {"name": "Item 1", "isSelected": "active"},  
        {"name": "Item 2", "isSelected": ""}
    ]
}

参见:http://jsfiddle.net/tTfWM/

参见:http://docs.angularjs.org/api/ng.directive: ngClass

其他回答

只是添加了一些对我来说有用的东西,经过大量的搜索……

<div class="form-group" ng-class="{true: 'has-error'}[ctrl.submitted && myForm.myField.$error.required]">

希望这有助于您的成功开发。

=)

无文档的表达式语法:伟大的网站链接…=)

这是我在工作中多次有条件的判断:

<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> &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
  <span ng-bind-html="eOption.eoName | to_trusted">2020 元</span>
</li>

这可能会被否决,但下面是我如何使用1.1.5的三元操作符来切换类,取决于表中的一行是第一行、中间一行还是最后一行——除非表中只有一行:

<span class="attribute-row" ng-class="(restaurant.Attributes.length === 1) || ($first ? 'attribute-first-row': false || $middle ? 'attribute-middle-row': false || $last ? 'attribute-last-row': false)">
</span>

如果你有一个应用于很多元素的公共类,你可以创建一个自定义指令来添加这个类,比如ng-show/ng-hide。

这个指令会在按钮被点击时添加类'active'

module.directive('ngActive',  ['$animate', function($animate) {
  return function(scope, element, attr) {
    scope.$watch(attr.ngActive, function ngActiveWatchAction(value){
      $animate[value ? 'addClass' : 'removeClass'](element, 'active');
    });
  };
}]);

更多信息

这里有一个更简单的解决方案:

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>