trying to use ng-class with multiple conditions

2.9k views Asked by At

I'm trying to set up an ng-class to work on a div with two conditions:

ng-class="(accounts.length == 1 && account.cardName =='Cash') ? 'one-dash-cash' : ''"

and

ng-class="(accounts.length == 1 && account.cardName =='Points') ? 'one-dash' : ''"

What's the best way to accomplish this? I've read that I shouldn't have all this logic in the HTML, but I'm not sure how to do this.

Thanks in advance..

3

There are 3 answers

0
Abhishek Jain On

The answers provided by Shankar and user3227295 are correct and work correctly, but there are 2 alternate methods that you can use. I am not saying that they are better than the ones already mentioned, but it is better to be aware of them. Here is a plunker showing all three approaches.

  1. Put your logic in controller than inline (which I would use)

    $scope.isOneDash = $scope.accounts.length == 1 && $scope.account.cardName =='Points';
    $scope.isOneDashCash = $scope.accounts.length == 1 && $scope.account.cardName =='Cash'; 
    

And in your html

<div ng-class="{
       'one-dash-cash': isOneDashCash,
        'one-dash': isOneDash
    }">Hello</div>
  1. Use an attribute directive. This may be an overkill for your case, but surely a way.

    app.directive('dashOrCash', function() {
      return {
    retrict: 'A',
    link: function(scope, elem) {
      if (scope.accounts.length == 1 && scope.account.cardName =='Cash') {
        elem[0].classList.add('one-dash-cash');
      }
      if (scope.accounts.length == 1 && scope.account.cardName =='Points') {
        elem[0].classList.add('one-dash');
      }
    }
      }})
    
1
user3227295 On
ng-class="{'one-dash-cash':accounts.length == 1 && account.cardName =='Cash','one-dash':accounts.length == 1 && account.cardName =='Points'}"
0
ShankarSangoli On

You can pass a js map to ng-class.

<div ng-class="{
       'one-dash-cash':accounts.length == 1 && account.cardName =='Cash',
        'one-dash':accounts.length == 1 && account.cardName =='Points'
}"></div>

So based on the condition appropriate class will be applied to the element.

ng-class reference https://docs.angularjs.org/api/ng/directive/ngClass