$routeParams is empty in main controller

后端 未结 6 873
北海茫月
北海茫月 2020-12-15 04:41

I have this piece of layout html:


  
6条回答
  •  庸人自扰
    2020-12-15 05:26

    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
      });
    );
    

提交回复
热议问题