2014-04-03 32 views
1

我想有条件地显示一个基于存储在父范围内的布尔值的指令。我无法弄清楚为什么以下不起作用。通过,“不工作”我的意思是既不显示指令。Angular JS:ng开关布尔不工作

<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”在我的测试情况下被设置为“假”。如果我在指令上面添加{{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-开关时,从他们要么会显示指令属性。所以我知道问题是我的切换。

+0

您可以显示'account-item'指令中的内容吗? – raina77ow

回答

2

你的NG-开关的使用工作在这个简化的演示,当然没有你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

+0

我在这个[Plunkr](http://plnkr.co/edit/cy8AfaBTlRwsEplHTBer?p=preview)中为这些项目添加了一个(非常简单的)'ng-repeat',似乎工作正常。所以'account-item'应该是这里的关键。 – raina77ow

1

由于ngSwitchWhen有800优先级,你需要一个更高的优先级顺序设置为自定义指令(即account-item),它由ngSwitchWhen指令被处理之前进行编译。例如:

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