Angular,$route.current 返回未定义,但 $route 有一个 .current 属性

Angular, $route.current returning undefined, but $route has a .current property

我有一个控制器:

app.controller('NavbarController', ['$scope', '$route', function($scope, $route) {
   console.log($route);
   console.log($route.current)
}]);

但是当我尝试使用 $route.current 时,我得到了未定义,我不知道为什么当我 console.log($route)

时 $route 具有属性

我有

.when('/', {
      templateUrl: '/home',
      controller: 'HomeController',
      activeTab: 'home'
    }).

我需要访问 $route.current.$$route.activeTab 以便获取变量并设置适当的 class。

完全控制器:

var app = angular.module('PugIt', ['ngRoute', 'ui.bootstrap'])

app.config(function($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: '/home',
      controller: 'HomeController',
      activeTab: 'home'
    }).
    when('/help', {
      templateUrl: '/help',
      controller: 'HelpController',
      activeTab: 'help'
    }).
    when('/donate', {
      templateUrl: '/donate',
      controller: 'DonateController',
      activeTab: 'donate'
    }).
    when('/server', {
      templateUrl: '/server',
      controller: 'ServerController',
      activeTab: 'server'
    }).
    when('/server/new', {
      templateUrl: '/server/new',
      controller: 'NewServerController',
      activeTab: 'serverNew'
    }).
    otherwise({
      redirectTo: '/'
    });
});

app.controller('HomeController', ['$scope', '$route', function($scope, $route) {

}]);

app.controller('HelpController', ['$scope', '$route', function($scope, $route) {

}]);

app.controller('DonateController', ['$scope', '$route', function($scope, $route) {

}]);

app.controller('ServerController', ['$scope', '$route', function($scope, $route) {

}]);

app.controller('NewServerController', ['$scope', '$route', function($scope, $route) {
}]);

app.controller('NavbarController', function($scope, $rootScope) {
  $route.activeTab = $route.current.$$route.activeTab;
});

然后将活动 class 设置为:

 // Navbar
    <div ng-controller="NavbarController">
        <li ng-class="{'active': activeTab == 'home'}"><a href="#/">Home</a></li>
    </div>
    // End of Navbar
    <div ng-view></div>

很可能在加载 NavController 时未设置当前路线。

你在你的 NavController 中可以做的是照看 $route.current,并且 当它得到 set\changed 时,在 watch handler

中实现逻辑
$scope.$watch(function() {
   return $route.current;
},function(newValue,oldValue) {
    //implement logic here
});

既然你需要跟踪你的路线,你绝对可以$watch进行更改:

.controller('NavbarController', function($scope, $route) {
   $scope.$route = $route;
   $scope.$watch("$route.current.$$route.activeTab", function(v){
     $scope.activeTab = v;
   }
});

但这会造成不必要的 $watch。这还不错,因为它只有一个,但是听 $routeChangeSuccess 事件会更干净:

.controller('NavbarController', function($scope, $route) {
   $scope.$route = $route;
   $scope.$on("$routeChangeSuccess", function(event, current, previous){
     $scope.activeTab = current.$$route.activeTab;
   }
});