Search code examples
angularjsangularjs-ng-repeatng-class

AngularJS: ng-repeat and ng-class


I've a problem with ng-repeat and ng-class. I want to apply class only if the param "sel" is true. My data is about this: people = [{"id":0,"name":"Simone","sel":true},{"id":1,"name":"Maria","sel":false},{"id":2,"name":"Marco","sel":false}]

In my html page I've:

<li ng-repeat="person in people" id="person-{{person.id}}">
        <span ng-class="{person-select: person.sel == 'true'}">{{person.name}}</span>
</li>

But it doesn't work.. Where I'm wrong? I tried with {{person.name}}-{{person.sel}} and it print "Simone-true .. Maria-false .. Marco-false".


Solution

  • The first problem with your code is that you are comparing a boolean value with a string.

    true == 'true' // will return false
    

    The second problem is that the name of the class is not wrapped in '.

    Bellow code fixes both issues:

    <li ng-repeat="person in people" id="person-{{person.id}}">
        <span ng-class="{'person-select': person.sel}">{{person.name}}</span>
    </li>