Use links to change ng-switch

Charlie Andrews picture Charlie Andrews · Jun 10, 2013 · Viewed 7.1k times · Source

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?

Answer

user3123032 picture user3123032 · Oct 19, 2016

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>