user264230
user264230

Reputation: 650

Using class with angular vs ng-class while using a mixed expression

I have a div that I want to give a dynamic class with AngularJS.

The div is withing an ng-repeat statement where lang.prefix is first en then sv

Using the following code works and sets the class to i-flag-en than i-flag-sv, but is it correct?

<div class="float-left flag i-flag-{{lang.prefix}}"></div>

I know there exist a ng-class directive which can be used to dynamically set the class of an element with AngularJS.

I think I read somewhere in a book, that the normal class directive not should be used to set the class property dynamically with AngularJS because of the way Angular manipulates the dom.

However, the following code does not work:

<div class="float-left flag" ng-class="i-flag-{{lang.prefix}}"></div>

and I rather want to set the class in this way instead of creating another scope variable.

Is it bad practice to use the class attribute with AngularJS to dynamically set the class? Does it work all the time even if it would be bad practice?

Upvotes: 21

Views: 15056

Answers (1)

ryeballar
ryeballar

Reputation: 30098

The book you have mentioned may have talked about the problems of using ng-class and class {{}} interpolations together wherein updates in the interpolation removes the ng-class classes, this problem has already been resolved, reference. Thus, using interpolation within class attributes is totally fine, and does not break good practice because both has its own quirks.

Your usage of ng-class however is incorrect, you have to concatenate the literal string value with your scope string variable:

<div class="float-left flag" ng-class="'i-flag-' + lang.prefix"></div>

but I think it is much preferable to use your first example instead:

<div class="float-left flag i-flag-{{lang.prefix}}"></div>

Upvotes: 26

Related Questions