Search code examples
angularjsangularjs-serviceangularjs-routing

Angular JS: how to change view in ng-view


I have navbar,sidebar and container. for each item in navbar have different sidebar.
Ex:
- If i click Nav A, it have sidebar A, B, C.
- and if i click Nav B, it have sidebar D, E, F

and for each sidebar have different data in container. anyone know how the logic for make that interface in angularjs.


Solution

  • It sounds to me like you want to show different content based on which Nav is selected, you can do something like this:

    HTML:

    <div data-ng-controller="nav-controller">
        <ul data-ng-view>
            <li data-ng-click="showSidebar('a');">Sidebar A</li>
            <li data-ng-click="showSidebar('b');>Sidebar B</li>
        </ul>
        <ul data-ng-view="sidebar">
            {{sidebarContent}}
        <ul>
    </div>
    

    Javascript inside controller:

    $scope.showSidebar = function(name){
        if(name == "a"){
            $scope.sidebarContent = "someCode for sidebar A";
        };
        if(name == "b"){
            $scope.sidebarContent = "someCode for sidebar B";
        };
    };
    

    Alternatively you could put the code in it's own template, and use the following:

    HTML:

        <div data-ng-include="{{sidebarContentUrl}}"></div>
    

    Javascript inside controller:

    $scope.showSidebar = function(name){
        if(name == "a"){
            $scope.sidebarContentUrl = "partials/sidebarA.tpl.html";
        };
        if(name == "a"){
            $scope.sidebarContentUrl = "partials/sidebarB.tpl.html";
        };
    };
    

    You could also include all the sidebars in one template, and hide them conditionally.