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?

Charlie Andrews
  • 1,457
  • 19
  • 28

2 Answers2

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>

user3123032
  • 341
  • 2
  • 3
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>
mfeingold
  • 7,094
  • 4
  • 37
  • 43