7

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.

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.