3

How would I use links to trigger an ng-switch?

My current html:

<ul class="nav nav-list bs-docs-sidenav affix sidenav">
    <li><a href="#" ng-click="page='resources'">Resources</a></li>
    <li><a href="#" ng-click="page='users'">Users</a></li>

</ul>

<div ng-switch on="page">
    <div ng-switch-when="resources">
        <h1>resources Div</h1>
    </div>
    <div ng-switch-when="users">
        <h1>Users</h1>
    </div>
    <div ng-switch-default>
        <h1>Default</h1>
    </div>
</div>

My controller:

function Ctrl($scope) {
    $scope.page = 'users';
}

What am I missing?

5
  • 1
    And what happens when you run this code? Commented Jun 10, 2013 at 18:39
  • nothing. If I change the expressions that change page to a function that changes page and then console.log($scope.page) I can see that page is getting changed, but the switch doesn't occur. Commented Jun 10, 2013 at 18:41
  • Works here - jsfiddle.net/Dogbert/uYMSN Commented Jun 10, 2013 at 18:45
  • I wonder why this is not working for me. Commented Jun 10, 2013 at 19:01
  • @Dogbert snippet is working correctly. Can we select an answer for this question? Commented Sep 3, 2017 at 22:47

2 Answers 2

4

I stumbled on a similar problem and solved it by using an object rather then a property on the scope so that the values are not overridden by the ng-switch directive.

The difference between the question asked and this solution is that I change the page value from withing the ng-switch scope.

Declare nav object in the controller

$scope.nav = {
                 page : 1
             }

HTML

<div ng-switch="nav.page">
<div ng-switch-when="1">
    First page
    <a href="#" ng-click="nav.page=2">Resources</a>
</div>
<div ng-switch-when="2">
    Second page
    <a href="#" ng-click="nav.page=3">Resources</a>
</div>
<div ng-switch-when="2">
    Third page
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Would love to know why this is the case for this setup. Thanks for the answer though, really helped me out!
2

You have to bind your controller to the top level element. Here is the fiddle

HTML:

<div ng-app ng-controller="Ctrl">
     <ul class="nav nav-list bs-docs-sidenav affix sidenav">
         <li><a href="#" ng-click="page='resources'">Resources</a></li>
         <li><a href="#" ng-click="page='users'">Users</a></li>

     </ul>
     <div ng-switch on="page">
        <div ng-switch-when="resources">
           <h1>resources Div</h1>
        </div>
        <div ng-switch-when="users">
           <h1>Users</h1>
        </div>
        <div ng-switch-default>
           <h1>Default</h1>
        </div>
     </div>
</div>

1 Comment

My controller is bound in the routeProvider in app.js, so that does not help my problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.