leaksterrr
leaksterrr

Reputation: 4167

Nested Angular Switches?

I'm building a MEAN SPA and the current page I'm working on displays the users in the database. I'm pretty new to Angular so I'm still trying to wrap my head around it.

I have a parent container of which the content is controlled by an <ng-switch> and switches to show the relevant content depending on whether the user has clicked 'view all' or 'add new'. This works fine.

What I'm aiming to do now is when the user clicks on a user that's displayed in 'view-all', I want the content to switch to a view containing that users details where they can then go and edit the profile etc. What would be the best way to achieve this?

My HTML is set up like so:

Main staff view

<div class="staff" ng-controller="staffController">
    <div class="side-menu">
        <h2>Staff</h2>
        <ul>
            <li><a ng-click="tab='view-all'"><i class="fa fa-user"></i> View All</a></li>
            <li><a ng-click="tab='add-new'"><i class="fa fa-plus"></i> Add New</a></li>
        </ul>
    </div>

    <div class="page-content" ng-switch on="tab">
        <div ng-switch-when="view-all" class="tab-content">
            <staff-view-all></staff-view-all>
        </div>
        <div ng-switch-when="add-new" class="tab-content">
            <staff-add-new></staff-add-new>
        </div>
    </div>
</div>

Directives:

.directive('staffViewAll', function () {
        return {
            restrict: 'E',
            templateUrl: 'partials/staff/view-all.ejs'
        }
    })

.directive('staffAddNew', function () {
        return {
            restrict: 'E',
            templateUrl: 'partials/staff/add-new.ejs'
        }
    })

view-all.ejs

<h2>View all staff</h2>

{{ users.length }} users in system

<ul>
    <li ng-repeat="user in users"> <!-- click this and you see the singular view -->
        <img ng-src="{{user.avatar}}?dim=100x100" />
        <h3>{{user.username}}</h3>
        <h4>{{user.email}}</h4>
    </li>
</ul>

Upvotes: 0

Views: 162

Answers (1)

link
link

Reputation: 1676

Use another ng-switch to switch to detailed view for the selected user.

Something like this: jsfiddle

<div ng-switch-when="list">
    <ul>
        <li ng-repeat="fruit in fruits">
            <a href="#"ng-click="showDetail(fruit)">{{fruit}}</a>
        </li>
    </ul>
</div>
<div ng-switch-when="details">
    <p>Details for {{ selectedFruit }}</p>
    <a href="#" ng-click="showList()">Back to list</a>
</div>

Controller:

    $scope.showDetail = function (fruit) {
        $scope.selectedFruit = fruit;
        $scope.moduleState = 'details';
    }

    $scope.showList = function()
    {
        $scope.moduleState = 'list';
    };

Upvotes: 1

Related Questions