简体   繁体   中英

Angular ng-class if else

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?

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'">

您可以使用三元运算符表示法:

<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)]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM