0

I would like to style a text by its length. So true is red and false is green. I use ng-class with expression. It's possible to change the css after a user click?

This is a plunkr: http://plnkr.co/edit/ndCqpZaALfOEiYieepcn?p=preview

<div>
 <p ng-class="{true:'green',false:'red'}[name.length>3 && toggle]">{{name}}</p>

 <p><b>Length: </b> {{name.length}} character(s)</p>

 <button ng-click="toggle=!toggle">Toggle class</button> 
</div>
2
  • don't you have to make a controller function for ng-click? Does inline code work? Commented Sep 11, 2013 at 1:00
  • 1
    No need for controller Commented Sep 11, 2013 at 1:09

1 Answer 1

1

Initially, toggle is undefined, which I think is causing an error when evaluating the expression [name.length>3 && toggle]. Then when you click the button, the opposite of undefined is true, so then your toggle starts working as you expect.

To fix this, you can use ng-init to evaluate an expression before the views are processed.

For example, if you change your div to be:

<div ng-init="toggle = true">

then the class starts out as green initially.

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

1 Comment

In the documentation I never noticed this ng-init...Thanks a lot

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.