简体   繁体   中英

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. If I add {{userIsAuthenticated}} above the directives 'false' is output as expected.

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. So I'm know the problem is my ng-switch.

Your usage of ng-switch works in this simplified demo, of course without your account-item directive: http://plnkr.co/AppN8xmFeIwjaP631lj7

Without seeing the code for account-item , it is hard to guess what might be interfering with it. You might consider using ng-if to handle displaying one item or another.

<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

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. Eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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