0

I have many tags in HTML with ng-class directive which looks like:

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'"

I am just wondering if there is any way to write ng-class directive in more compact way? May be move the condition to controller?

ceth
  • 44,198
  • 62
  • 180
  • 289
  • 1
    Possible duplicate of [What is the best way to conditionally apply a class?](http://stackoverflow.com/questions/7792652/what-is-the-best-way-to-conditionally-apply-a-class) – Makoto Nov 19 '15 at 18:48

2 Answers2

1

For ng-class there isn't a very much shorter way. You could use the object notation for it: ng-class="{'item-detail-section-line-selected': group == currentGroup, 'item-detail-section-line-unselected': group != currentGroup}" In your case it might not be shorter necessarily.

Another approach is to move the logic to an ng-if instead. Although you gain some watchers compared to the initial approach, it would be more readable and manageable than using ng-class as you can use functions using the 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"
Erwin
  • 3,298
  • 2
  • 15
  • 22
1

Moving the condition to a controller is not a bad idea to clean up your view.

// 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)"
Matt MacLeod
  • 438
  • 2
  • 5
  • 17