2015-11-19 72 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" 
相關問題