有没有办法以更紧凑的方式编写ng-class指令

时间:2015-11-19 18:45:20

标签: angularjs

我在HTML中有许多带ng-class指令的标签,如下所示:

div(class="item-detail-section-line", ng-repeat="group in FieldGroups")
   a(href="", ng-click="groupClick(group)",
              ng-class="group == currentGroup ? 'item-detail-section-line-selected' : " +
              "'item-detail-section-line-unselected'"

我只是想知道是否有办法以更紧凑的方式编写ng-class指令?可以将条件移到控制器上吗?

2 个答案:

答案 0 :(得分:1)

对于ng-class,没有太短的方法。您可以使用对象表示法: ng-class="{'item-detail-section-line-selected': group == currentGroup, 'item-detail-section-line-unselected': group != currentGroup}" 在你的情况下,它可能不一定短。

另一种方法是将逻辑移到ng-if。尽管与初始方法相比,您获得了一些观察者,但它比使用ng-class更具可读性和可管理性,因为您可以使用ng-if使用函数:

div(class="item-detail-section-line", ng-repeat="group in FieldGroups")
   a(href="", ng-click="groupClick(group)",
              ng-if="group == currentGroup"
              class="item-detail-section-line-selected"
   a(href="", ng-click="groupClick(group)",
              ng-if="group != currentGroup"
              class="item-detail-section-line-unselected"

答案 1 :(得分:1)

将条件移动到控制器清理视图并不是一个坏主意。

// In your controller
$scope.setDetailLineSelectedClass = 
    {
      'item-detail-section-line-selected': $scope.group == $scope.currentGroup, 
      'item-detail-section-line-unselected': $scope.group != $scope.currentGroup
    }


// In your view 
ng-class="setDetailLineSelectedClass"


// Using non-scope variable (created by ng-repeat)

// In your controller
$scope.setDetailLineSelectedClass = function(group){
    return {
      'item-detail-section-line-selected': group == $scope.currentGroup, 
      'item-detail-section-line-unselected': group != $scope.currentGroup
    }
}


// In your view 
ng-class="setDetailLineSelectedClass(group)"