简体   繁体   English

Angular ng-class if else

[英]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 如果页面被选中,则page.isSelected(1)为TRUE,否则为FALSE

<div id="homePage" ng-class="{ center: page.isSelected(1) }">

I therefore want you if: 因此,如果:

isSelected is TRUE: center isSelected为TRUE:center

isSelected is FALSE: left isSelected为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. John Conderyeballar的答案都是正确无误的。

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. John的缺点在于每个$ digest循环必须做出两个决定(它必须决定是否添加/删除center ,并且必须决定是否添加/删除left ),显然只需要一个。

  • 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). Ryeballar依赖于三元运算符,它可能会在某些时候被删除(因为视图不应该包含任何逻辑)。 (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)]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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