1

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.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Nick
  • 19,198
  • 51
  • 185
  • 312

2 Answers2

2

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

j.wittwer
  • 9,497
  • 3
  • 30
  • 32
  • I've added a (very simple) `ng-repeat` to these items in this [Plunkr](http://plnkr.co/edit/cy8AfaBTlRwsEplHTBer?p=preview), seems to work ok. So indeed `account-item` should be the key here. – raina77ow Apr 03 '14 at 20:49
1

Since ngSwitchWhen has a priority of 800, you need to set a higher priority to your custom directive (i.e. account-item) in order for it to be compiled before being process by the ngSwitchWhen directive. E.g.:

.directive('accountItem', function () {
    return {
        ...
        priority: 900,
        ...
    };
});
gkalpak
  • 47,844
  • 8
  • 105
  • 118