Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngClass style with dash in key

Tags:

angularjs

I hope this saves someone a headache with styles that use dashes, especially since bootstrap has become so popular.

I am using angular 1.0.5 by way of

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>

In the ngClass documentation, the example is simple, but it also mentions the expression can be a map of class names to boolean values. I was trying to use the "icon-white" style on my icon as shown in the bootstrap documentation, depending on a boolean variable.

<i class="icon-home" ng-class="{icon-white: someBooleanValue}">

The line above does not work. The class is not appended with icon-white when someBooleanValue is true. However, if I change the key to iconWhite, it is successfully added to the list of class values. How would one add a value with a dash?

like image 327
Foo L Avatar asked Oct 02 '22 02:10

Foo L


People also ask

How do you write ngClass with condition?

You can use [ngClass] or [class. classname], both will work the same. Both will work the same!

Can we use NgStyle and ngClass together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

What is the difference between NgStyle and ngClass?

ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute.


2 Answers

After hours of hacking around, it turns out the dash gets interpolated! Quotes are needed.

<i class="icon-home" ng-class="{'icon-white': someBooleanValue}">

UPDATE:

In older versions of Angular, using a backslash also does the trick, but not in the newer versions.

<i class="icon-home" ng-class="{icon\-white: someBooleanValue}">

The former is probably preferred, since you can more easily search for it in your favorite editor.

like image 368
Foo L Avatar answered Oct 19 '22 19:10

Foo L


\'icon-white\' works as well (with AngularJS 1.2.7)

like image 11
Bromoxid Avatar answered Oct 19 '22 20:10

Bromoxid