The $routeParams
service is populated asynchronously. This means it will typically appear empty when first used in a controller.
To be notified when $routeParams
has been populated, subscribe to the $routeChangeSuccess
event on the $scope
. (If you're in a component that doesn't have access to a child $scope
, e.g., a service or a factory, you can inject and use $rootScope
instead.)
module.controller('FooCtrl', function($scope, $routeParams) {
$scope.$on('$routeChangeSuccess', function() {
// $routeParams should be populated here
});
);
Controllers used by a route, or within a template included by a route, will have immediate access to the fully-populated $routeParams
because ng-view
waits for the $routeChangeSuccess
event before continuing. (It has to wait, since it needs the route information in order to decide which template/controller to even load.)
If you know your controller will be used inside of ng-view
, you won't need to wait for the routing event. If you know your controller will not, you will. If you're not sure, you'll have to explicitly allow for both possibilities. Subscribing to $routeChangeSuccess
will not be enough; you will only see the event if $routeParams
wasn't already populated:
module.controller('FooCtrl', function($scope, $routeParams) {
// $routeParams will already be populated
// here if this controller is used within ng-view
$scope.$on('$routeChangeSuccess', function() {
// $routeParams will be populated here if
// this controller is used outside ng-view
});
);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…