【问题标题】:How to Use Ternary With ng-if?如何在 ng-if 中使用三元?
【发布时间】:2015-07-27 18:43:44
【问题描述】:

例如,我想显示元素 if $scope.test === 'hi"。我如何做到这一点?

我试过这个:

<div ng-if = " {{test}} == 'hi' ? true : false "> 
  Show this if $scope.test is equal to 'hi' 
</div>

示例here 似乎不起作用。 My fail plunker.

【问题讨论】:

  • 您是否故意使用 Angular 1.0.5?这是一个 1.4 plnkr.co/edit/3XHe1Ngw1Ntv5FCTBJwA?p=preview
  • 谢谢seb。不,我只是在谷歌上搜索了一个 angular plunk,因为我懒得写“ng-app = 'blah'”和“ng-controller = 'blah2'”。甚至不是讽刺。我们需要一些默认的 plunk 模板开始.

标签: angularjs


【解决方案1】:

您不需要三元组,因为 ng-if 需要一个布尔值。这样就可以了:

<div ng-if = "test == 'hi'"> 
  Show this if $scope.test is equal to 'hi' 
</div>

如果你愿意,你仍然可以使用三元组,只是不需要插入变量:test == 'hi' ? true : false


问题在于您的真正旧的 Angular 版本。看到它与 1.3 一起使用:http://plnkr.co/edit/cKZkOe1O4EBiIWeirlZ2?p=preview

【讨论】:

【解决方案2】:

嗯。您不要在ng-if 中使用{{}}

<div ng-if = " test == 'hi'"> 
Show this if $scope.test is equal to 'hi' 
</div>

以上作品


编辑

这在您的 plunker 中失败了,因为 ng-if 指令是在 Angular 1.1.5 之后提供的,您使用的是 1.0.5。

工作版本

http://plnkr.co/edit/3XHe1Ngw1Ntv5FCTBJwA

【讨论】:

  • 我的代码和另一个编辑器也失败了。这是我在谷歌搜索解决方案之前尝试的第一件事。
  • 我接受 Shomz 的回答是因为他是第一个,但非常感谢您的帮助,点赞。
【解决方案3】:

这里不需要三元表达式,使用ng-show即可。

<div ng-show="test"></div>

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2017-02-28
    相关资源
    最近更新 更多