37

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?

Garu
  • 1,159
  • 2
  • 10
  • 15
  • Possible duplicate of [angular ng-class if-else expression](http://stackoverflow.com/questions/18172573/angular-ng-class-if-else-expression) – Castro Roy Aug 04 '16 at 22:49

3 Answers3

74

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'">
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • [This is good sample for using ng-class without associating the value to model](https://codepen.io/DevelopIntelligenceBoulder/pen/rewObY/) – Abhijeet Apr 05 '17 at 11:01
27

You can use the ternary operator notation:

<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">
ryeballar
  • 29,658
  • 10
  • 65
  • 74
9

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)]"
Community
  • 1
  • 1
gkalpak
  • 47,844
  • 8
  • 105
  • 118
  • In light of your 2nd statement, is it possible that the `ng-class="[]"` notation can be removed as well? if not, then it is still possible to do it like this: `ng-class="[page.isSelected(1)? 'center : 'left']"` – ryeballar Aug 18 '14 at 18:16
  • The ternay operator will be removed from the "abilities" of the $parser (at least that's what Igor Minar is hoping for :)). This means that no expression containing the trnary operator will be parsable as an Angular Expression. – gkalpak Aug 18 '14 at 18:19