有什么办法来写纳克级的指令在更紧凑的方式
问题描述:
我在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-类指令更紧凑的方式?可以把条件移到控制器上?
答
移动条件控制器是不是一个坏主意清理你的观点。
// 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)"
答
对于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"
的可能的复制【什么是有条件地应用类的最佳方法是什么?(http://stackoverflow.com/questions/7792652/what-is-the-best-way-to-conditionally-apply -a-class) – Makoto