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

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


当前回答

如果你正在使用angular pre v1.1.5(即没有三元操作符),并且你仍然想要在这两种情况下使用等效的方法来设置值,你可以这样做:

ng-class="{'class1':item.isReadOnly == false, 'class2':item.isReadOnly == true}"

其他回答

如果你不想像我一样把CSS类名放在控制器中,这里有一个我从v1时代以前就使用的老技巧。我们可以编写一个表达式,直接计算所选的类名,不需要自定义指令:

ng:class="{true:'selected', false:''}[$index==selectedIndex]"

请注意使用冒号的旧语法。

还有一种新的更好的有条件地应用职业的方法,比如:

ng-class="{selected: $index==selectedIndex}"

Angular现在支持返回对象的表达式。该对象的每个属性(名称)现在都被视为一个类名,并根据其值应用。

然而,这些方式在功能上并不相等。这里有一个例子:

ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]"

因此,我们可以通过将模型属性映射到类名来重用现有的CSS类,同时将CSS类排除在Controller代码之外。

我最近遇到了一个类似的问题,决定只创建一个条件过滤器:

  angular.module('myFilters', []).
    /**
     * "if" filter
     * Simple filter useful for conditionally applying CSS classes and decouple
     * view from controller 
     */
    filter('if', function() {
      return function(input, value) {
        if (typeof(input) === 'string') {
          input = [input, ''];
        }
        return value? input[0] : input[1];
      };
    });

它接受一个参数,该参数是一个2元素数组或一个字符串,它被转换为一个数组,并将一个空字符串作为第二个元素:

<li ng-repeat="item in products | filter:search | orderBy:orderProp |
  page:pageNum:pageLength" ng-class="'opened'|if:isOpen(item)">
  ...
</li>

如果你正在使用angular pre v1.1.5(即没有三元操作符),并且你仍然想要在这两种情况下使用等效的方法来设置值,你可以这样做:

ng-class="{'class1':item.isReadOnly == false, 'class2':item.isReadOnly == true}"

我建议你用一个返回true或false的函数来检查控制器中的条件。

<div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>

在你的控制器中检查情况

$scope.getTodayForHighLight = function(today, date){
return (today == date);
}

这可能会被否决,但下面是我如何使用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>