Reputation: 3137
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>
Upvotes: 0
Views: 199
Reputation: 7014
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.
Upvotes: 1