2015-11-19 70 views
0

我在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-类指令更紧凑的方式?可以把条件移到控制器上?

+1

的可能的复制【什么是有条件地应用类的最佳方法是什么?(http://stackoverflow.com/questions/7792652/what-is-the-best-way-to-conditionally-apply -a-class) – Makoto

回答

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)" 
+0

'group'在我的情况下不是$ scope变量。它是ng-repeat指令的一部分。如果我在这种情况下正确理解,我不能使用此代码。 – demas

+0

它在哪里得到它的值,ng-init? –

+0

ng-repeat。有我的问题中的代码。 – demas

1

对于ng级而言,并不是一个非常简短的方法。你可以使用它的对象符号: ng-class="{'item-detail-section-line-selected': group == currentGroup, 'item-detail-section-line-unselected': group != currentGroup}" 在你的情况下,它可能不会更短。

另一种方法是将逻辑移至ng-if。虽然你获得一些观察家相比最初的方法,这将是比使用纳克级更具可读性和可管理性,你可以使用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" 
相关问题