[英]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
以便獲取變量並設置適當的類。
完整控制器:
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;
});
然后使用以下方法設置活動類:
// Navbar
<div ng-controller="NavbarController">
<li ng-class="{'active': activeTab == 'home'}"><a href="#/">Home</a></li>
</div>
// End of Navbar
<div ng-view></div>
由於您需要跟蹤自己的路線,因此絕對可以$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;
}
});
加載NavController
時,很可能未設置當前路徑。
您可以在NavController
執行的NavController
是監視$route.current
,並在其設置\\更改后,在監視處理程序中實現邏輯
$scope.$watch(function() {
return $route.current;
},function(newValue,oldValue) {
//implement logic here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.