In AngularJS, can I use current route in ngSwitch outside of ngView

前端 未结 4 1997
日久生厌
日久生厌 2021-01-12 18:42

I am trying to change the page header depending on current view. The header is outside of ngView. Is that possible or do I need to put the header inside the view?

My

4条回答
  •  难免孤独
    2021-01-12 19:33

    A nice aproach for solving this is maybe to inject $route in your controller and then use it to grab the current route name.

    app.controller('YourController', function($scope, $route){
        $scope.pagename = $route.current.$$route.name;
    });
    

    And you have to name your routes like the following:

    app.config(['$routeProvider',
      function($routeProvider) {
        $routeProvider.
          when('/product-list', {
            templateUrl: 'views/product-list.html',
            controller: 'ProductsController',
            name: 'product-list'
          }).
          when('/home', {
            templateUrl: 'views/home.html',
            controller: 'HomeController',
            name: 'home'
          }).
          otherwise({
            redirectTo: '/'
          });
      }]);
    

    So when you load a route,the controller will read the current route name and pass it to the view in your pagename variable. Then the view will pick it up and display the correct view as you need.

    Hope it helps :)

提交回复
热议问题