Search code examples
javascriptcssangularjsng-class

Angularjs ng-class class order/precedence


EDIT:It turns out to be a confusion on my side, pls see my own answer.

I came across a strange behavior when attempting to reorder the precedence of multiple classes in ng-class.

ng-class="{'e':($index%2>0),'btn-primary':($index>3)}"

http://jsfiddle.net/6JjFM/1/

The thing is that no matter how you change the order of the expressions in ng-class it always seems to apply the class which is last in the stylesheet(ie in the css if you put the .btn-primary below .e it will start using the background-color of .btn-primary). Same thing occurs if I use the ng-class-even to put the .e class. If you actually inspect the code with chrome it shows up the order to be "btn-primary e" however the background-color of .e does not override the one of btn-primary.

Is there some way to change the precedence of the classes in the ng-class using angular without using css tricks such as !important etc.


Solution

  • Your problem is not actually on ng-class, as I see he work as how he design for.

    Solution 1:
    Yes, use CSS trick. Add below style to your stylesheet:

    .e.btn-primary{
        background-color: #F5F5F5;
    }
    

    It will now use e background color.

    Solution 2:
    Use ng-style

    <li 
        class="li" 
        ng-class="{'btn-primary':($index>3),'e':($index%2>0)}" 
        ng-repeat="row in rows"
        ng-style="$index%2>0 && {'backgroundColor': '#F5F5F5'}"
        >{{row}}</li>
    

    ng-style will add inline style to the element, and it will overwrite onfile stylesheet.