Angularjs 有没有办法以更简洁的方式编写ng类指令

Angularjs 有没有办法以更简洁的方式编写ng类指令,angularjs,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' : " +

我在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类指令?可能是将条件移动到控制器?

对于ng类,没有更短的方法。您可以使用对象表示法:

ng class=“{'item-detail-section-line-selected':group==currentGroup,'item-detail-section-line unselected':group!=currentGroup}”
在您的情况下,它可能不一定更短

另一种方法是将逻辑移到
ng if
。尽管与最初的方法相比,您获得了一些观察者,但它比使用ng类更具可读性和可管理性,因为您可以使用
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"

将条件移动到控制器对于清理视图来说不是一个坏主意

// 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)"

在我的情况下,
的可能重复项不是$scope变量。它是ng repeat指令的一部分。如果我在本例中理解正确,我将无法使用此代码。它的值从何处获得,ng init?我已更新以添加一个使用非范围变量的示例,以满足您的用例