Thursday, May 9, 2024
127
rated 0 times [  128] [ 1]  / answers: 1 / hits: 16003  / 12 Years ago, sat, january 12, 2013, 12:00:00

Let's say I have the following menu structure:



    <li class=dropdown><img role=button class=dropdown-toggle data-toggle=dropdown ng-src={{avatarUrl}} />
<ul class=dropdown-menu pull-right role=menu>
<li ng-hide=user><a ng-click=openLoginDialog()>Login</a></li>
<li ng-show=user><a ng-click=logout()>Logout</a></li>
</ul>
</li>


I get the correct menu, but because I'm using ng-show/ng-hide, when I change user = false; programmatically in the controller, the login menu appears. I get why this is happening, but I'm not sure what approach to take when using Angular to prevent it. I tried an ng-repeat:



    <li class=dropdown><img role=button class=dropdown-toggle data-toggle=dropdown ng-src={{avatarUrl}} />
<ul class=dropdown-menu pull-right role=menu>
<li ng-repeat=action in actions><a ng-click={{action.command}}>{{action.name}}</li>
</ul>
</li>


with:



$scope.actions = [ {
name : Login,
command : openLoginDialog()
}, {
name : Logout,
command : logout()
} ];


But with that strategy, nothing happens with I click the menu item. I'm not sure what the appropriate Angular approach is to what I'm sure is a pedestrian use case.


More From » twitter-bootstrap

 Answers
9

Use ng-switch instead of ng-show/hide. ng-switch adds/removes elements from the DOM.



<ul class=dropdown-menu pull-right role=menu>
<li ng-switch=user>
<a ng-switch-when=true ng-click=logout()>Logout</a>
<a ng-switch-default ng-click=openLoginDialog()>Login</a>
</li>
</ul>


Update to handle @andyczerwonka's comment. Move the ng-switch up one or two levels. If spans inside ul don't bother you:



<ul class=dropdown-menu pull-right role=menu ng-switch=user>
<span ng-switch-when=true>
<li><a ng-click=logout()>Logout</a></li>
<li><a ng-click=preferences()>Preferences</a></li>
</span>
<span ng-switch-default>
<li><a ng-click=openLoginDialog()>Login</a></li>
</span>
</ul>


Otherwise, how about one span outside the ul:



<span ng-switch=user>
<ul class=dropdown-menu pull-right role=menu ng-switch-when=true>
<li><a ng-click=logout()>Logout</a></li>
<li><a ng-click=preferences()>Preferences</a></li>
</ul>
<ul class=dropdown-menu pull-right role=menu ng-switch-default>
<li><a ng-click=openLoginDialog()>Login</a></li>
</ul>
</span>


Fiddle showing both methods.


[#80914] Friday, January 11, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckenna

Total Points: 445
Total Questions: 109
Total Answers: 109

Location: Virgin Islands (U.S.)
Member since Sun, May 16, 2021
3 Years ago
;