I'd like to know how to do to make the False ng-class.
page.isSelected(1) is TRUE if the page if the page is selected, else FALSE
<div id="homePage" ng-class="{ center: page.isSelected(1) }">
I therefore want you if:
isSelected is TRUE: center
isSelected is FALSE: left
I tried:
<div id="homePage" ng-class="{ page.isSelected(1) 'center : 'left' }">
but it doesnt work.
I do not know what I'm doing wrong. Can you help me please?
This question is related to
javascript
html
angularjs
ng-class
Just make a rule for each case:
<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1) }">
Or use the ternary operator:
<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">
Both John Conde's and ryeballar's answers are correct and will work.
If you want to get too geeky:
John's has the downside that it has to make two decisions per $digest loop (it has to decide whether to add/remove center
and it has to decide whether to add/remove left
), when clearly only one is needed.
Ryeballar's relies on the ternary operator which is probably going to be removed at some point (because the view should not contain any logic). (We can't be sure it will indeed be removed and it probably won't be any time soon, but if there is a more "safe" solution, why not ?)
So, you can do the following as an alternative:
ng-class="{true:'center',false:'left'}[page.isSelected(1)]"
You can use the ternary operator notation:
<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">
Source: Stackoverflow.com