Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 739
user264230 Avatar asked Aug 01 '14 22:08

user264230


People also ask

Can I use class with NgClass?

yes , you can do it. Did you try it? What happened? You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.

Can we use NGIF and NgClass together?

javascript - ng-if and ng-class-even/odd doesn't work well together and won't get expected outout - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

What is the difference between class and NgClass in Angular?

ngClass is more powerful. It allows you to bind a string of classes, an array of strings, or an object like in your example. The above two lines of code is with respect to CSS class binding in Angular. There are basically 2-3 ways you can bind css class to angular components.

Can we have 2 NgClass?

Yes it does, I just had to use !


1 Answers

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>
like image 107
ryeballar Avatar answered Sep 21 '22 01:09

ryeballar