Question

Tried looking for an answer to this with no success.

Is there anyway to have the value of a property be the class name when using ng-class in angularJS?

An example of what I mean:

var things = [
        {
            a: "abc",
            aTrue: true
        }
];

Then in Angular (using ng-repeat in this instance)

<div ng-repeat="thing in things" ng-class="{thing.a: !!thing.aTrue}></div>

I'm looking for the class name to be "abc" - but this gives me a class name of "thing.a". Is this even possible, where am I going wrong?

Thanks in advance, your help is appreciated.

Was it helpful?

Solution

The reason that doesn't work is because it acts just like a Javascript object so you can't do this in javascript can you

var test = 'hello';

var object = {
    test: 'hi'
};

object[test] === undefined // true // or
object.hello === undefined // true 
object.test  === undefined // false 

So you can't create a key with a variable like that. so try something like this.

 ng-class="{ true: thing.a, false: '' }[thing.aTrue]"

Demo: http://jsfiddle.net/XzXzR/1/

what this does is this (explanation in javascript)

var test = {
   one: 'hello',
   two: 'world'
}['one'];

What does test equal?

test ===  Object {one: "hello", two: "world"} // false
test ===  Object {one: "hello"} // false
test ===  Object {two: "world"} // false
test === 'one'   // false
test === 'two'   // false
test === 'hello' // ** true **
test === 'world' // false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top