0

I am trying to conditionally apply a class to an element but I can't get the syntax correct

I have tried the following but it does not work.

ng-class="{foo: bar === "true"}"

bar is a boolean value.

Also, the element already has a class attribute. Will foo be appended to the list of classes?

1
  • You can also use javascript condtional operator there.. like as a?a:b Commented Feb 23, 2015 at 13:28

2 Answers 2

1

You shouldn't use the double quote on your evaluation, because it's closing your ng-class attribute. You can use the single quote if you want to check a string. In you're case, if bar is a boolean value, you don't have to use quotes at all :

ng-class="{foo: bar === true}"

which is equivalent to

ng-class="{foo: bar}"

In case of a string, use :

ng-class="{foo: bar === 'your_string'}"

If your element already has a class attribute, foo will be appended to the list.

Sign up to request clarification or add additional context in comments.

Comments

1
ng-class="{'checkedClass': trueVariable}

Here is a post explaning the same http://www.ecofic.com/about/blog/conditionally-apply-a-css-class-with-angularjs

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.