How to use ng-switch as a router for my pages with ngRoute & ngView?

前端 未结 1 1871
囚心锁ツ
囚心锁ツ 2021-01-17 01:08

Here is the highlevel skeleton of my Angular SPA. My application is about college degree offerings. In that engineering page has a separate left nav which is currently built

相关标签:
1条回答
  • 2021-01-17 01:54

    Not a good practice but here's what you want to do if you want to use ng-switch:

    In your html, as you write for example:

    <!-- don't forget to reference your app and your controller -->
    <button ng-click="goTo('/page1')">Go to page 1</button>
    <button ng-click="goTo('/page2')">Go to page 2</button>
    <div nav ng-switch on="pagename()">
         <div ng-switch-when="'/page1'"></div>
         <div ng-switch-when="'/page2'"></div>
    </div>
    <div ng-view> </div> 
    

    in js

    Config your routes
    app.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/page1', {
                    templateUrl: 'views/page1.html'
                }).
                when('/page2', {
                    templateUrl: 'views/page2.html'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }])
    

    and add the following in your controller:

    $scope.pagename = function() { return $location.path(); };
    
        $scope.goTo = function(page){
            $location.path(page);
        }
    

    In the html above, ng-switch will use the $location.path() variable to know which view to display.

    As I said this is not a good practice, because your controller isn't suppose to deal with routes.

    0 讨论(0)
提交回复
热议问题