【问题标题】:Angular JS: ng-switch on boolean not workingAngular JS:布尔值上的ng-switch不起作用
【发布时间】:2014-04-03 20:12:25
【问题描述】:

我正在尝试根据存储在父范围中的布尔值有条件地显示指令。我不知道为什么下面不起作用。 “不工作”是指两个指令都没有显示。

 <ul class="nav navbar-nav pull-right" ng-switch="userIsAuthenticated">
    <account-item item="accountMenuItem" ng-repeat="accountMenuItem in anonymousMenuItems" ng-switch-when="false"></account-item>
    <account-item item="accountMenuItem" ng-repeat="accountMenuItem in authenticatedMenuItems" ng-switch-when="true"></account-item>
</ul>

即使在我的测试用例中“userIsAuthenticated”设置为“false”,也不会显示任何指令。如果我在指令上方添加{{userIsAuthenticated}},则会按预期输出'false'。

我也试过这个:

 <ul class="nav navbar-nav pull-right" ng-switch={{userIsAuthenticated}}>
    <account-item item="accountMenuItem" ng-repeat="accountMenuItem in anonymousMenuItems" ng-switch-when={{false}}></account-item>
    <account-item item="accountMenuItem" ng-repeat="accountMenuItem in authenticatedMenuItems" ng-switch-when={{true}}></account-item>
</ul>

如果我从它们将显示的任一指令中删除条件 ng-switch-when 属性。所以我知道问题出在我的 ng-switch 上。

【问题讨论】:

  • 你能显示account-item指令中的内容吗?

标签: javascript angularjs ng-switch


【解决方案1】:

您对 ng-switch 的使用在这个简化的演示中有效,当然没有您的 account-item 指令: http://plnkr.co/AppN8xmFeIwjaP631lj7

如果没有看到account-item 的代码,很难猜出是什么干扰了它。您可以考虑使用ng-if 来处理显示一项或多项。

<ul>
  <div ng-if="!userIsAuthenticated">Content when not authenticated</div>
  <div ng-if="userIsAuthenticated">Content when authenticated</div>
</ul>

更新 还要确保绑定到对象属性,而不是原始布尔值。喜欢:user. authenticated

【讨论】:

  • 我在这个Plunkr 的这些项目中添加了一个(非常简单的)ng-repeat,似乎工作正常。所以确实account-item应该是这里的关键。
【解决方案2】:

由于ngSwitchWhen 的优先级为800,您需要为自定义指令(即account-item)设置更高的优先级,以便在ngSwitchWhen 指令处理之前对其进行编译。例如:

.directive('accountItem', function () {
    return {
        ...
        priority: 900,
        ...
    };
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 2013-12-26
    • 2013-10-21
    • 2018-04-30
    • 2016-12-01
    • 2016-11-03
    • 2016-09-04
    • 1970-01-01
    相关资源
    最近更新 更多