最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - object property value as class name, ng-class - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Sep 13, 2013 at 14:05 iConnor 20.2k14 gold badges66 silver badges97 bronze badges asked Sep 13, 2013 at 13:38 user1262360user1262360 731 silver badge3 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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/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
发布评论

评论列表(0)

  1. 暂无评论