简体   繁体   English

Angular JS:ng-switch on boolean不工作

[英]Angular JS: ng-switch on boolean not working

I am trying to conditionally display a directive based on a boolean value stored in the parent scope. 我试图根据存储在父作用域中的布尔值有条件地显示指令。 I can't figure out why the below does not work. 我无法弄清楚为什么以下不起作用。 By, "not work" I mean neither directives are displayed. 通过,“不工作”我的意思是既没有显示指令。

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

Neither directives are shown even thought "userIsAuthenticated" is set to 'false' in my test case. 即使在我的测试用例中将“userIsAuthenticated”设置为“false”,也没有显示任何指令。 If I add {{userIsAuthenticated}} above the directives 'false' is output as expected. 如果我在指令上面添加{{userIsAuthenticated}}{{userIsAuthenticated}}预期输出'false'。

I've also tried this: 我也试过这个:

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

If I remove the conditional ng-switch-when attribute from either of the directives they will display. 如果我从它们将显示的任一指令中删除条件ng-switch-when属性。 So I'm know the problem is my ng-switch. 所以我知道问题是我的ng-switch。

Your usage of ng-switch works in this simplified demo, of course without your account-item directive: http://plnkr.co/AppN8xmFeIwjaP631lj7 您对ng-switch的使用在此简化演示中有效,当然没有您的account-item指令: http//plnkr.co/AppN8xmFeIwjaP631lj7

Without seeing the code for account-item , it is hard to guess what might be interfering with it. 如果没有看到account-item的代码,很难猜出可能会干扰它的内容。 You might consider using ng-if to handle displaying one item or another. 您可以考虑使用ng-if来处理显示一个或另一个项目。

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

Update Also make sure you bind to an object property, instead of a primitive boolean. 更新还要确保绑定到对象属性,而不是基本布尔值。 Like: user. authenticated 喜欢: user. authenticated user. authenticated

Since ngSwitchWhen has a priority of 800, you need to set a higher priority to your custom directive (ie account-item ) in order for it to be compiled before being process by the ngSwitchWhen directive. 由于ngSwitchWhen的优先级为800,因此需要为自定义指令(即account-item )设置更高的优先级,以便在由ngSwitchWhen指令处理之前对其进行编译。 Eg: 例如:

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

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

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