Search code examples
angularjsng-class

How to correctly combine strings and variables when applying ng-class via an expression?


When my app initializes, the following implementation of ng-class works as expected and the class name is correctly applied. However, when the value of person.status changes during run time, the class stays the same.

Here's my code:

ng-class="{ 'avatar--{{ person.status }}' : myBool }"

How can I change the formatting so that when the value of person.status changes, so does my class?

Example: if person.status is set to online when the app initializes, the applied class is avatar--online. However if their status changes to offline in the current session, the class remains avatar--online.


Solution

  • I have not tried to use an angular expression in the class name portion of the ng-class. but you could achieve what you want with this implementation

    ng-class="{'avatar--online': person.status == 'online',
               'avatar--offline': person.status == 'offline'}"
    

    basically you can set two conditions in your ng-class implementation.

    Hope this helps.