如何从routeChangeSuccess angularjs获取rootScope值

时间:2015-12-30 02:01:13

标签: angularjs angularjs-scope

我正在尝试按照以下代码从AngularJs中的routeChangeSuccess获取函数中的rootScope值。但是当我使用console.log输出时,我无法说服为什么rootScope值为NULL。

$rootScope.updateCurrentUser = function () {
    $rootScope.loggedUser = "1";
};

$rootScope.$on('$routeChangeSuccess', function () {
    var path = $location.path();
    $rootScope.showIndex =
        path === LANG_PATH + '/';
    if ($rootScope.showIndex) {
        //undefined result found :(
        console.log('rootScope ' + $rootScope.loggedUser);
    }
});

$rootScope.updateCurrentUser();

1 个答案:

答案 0 :(得分:0)

很难说,因为你的例子没有显示处理程序附加的位置以及对<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li> <span class="node"> <span class="con">First</span> <span class="check">First Check</span> <img> <a title="high">abc</a> </span> </li> <li> <span class="node"> <span class="con">Second</span> <span class="check">Second Check</span> <img> <a title="high">def</a> </span> </li> <li> <span class="node"> <span class="con">Third</span> <span class="check">Third Check</span> <img> <a title="low">zwc</a> </span> </li> </ul>的更改位置,但如果它发生在控制器中,则可能不会发生此事件。

在广播事件之后才会创建控制器,并且在广播下一个$rootScope.loggedUser事件之前,当前视图的控制器将被销毁,这意味着如果你'',你将会错过这个事件。在控制器的$routeChangeSuccess事件中重新注销处理程序。

在下面的代码段中,当您更改路径时,您会在$destroy中看到正在处理的事件(以及$rootScope.eventLog更新),但在控制器中的处理程序中则不会。

.run
angular.module('app', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/main', {
      templateUrl: 'main.html',
      controller: 'MainCtrl'
    })
    .when('/other', {
      templateUrl: 'other.html',
      controller: 'OtherCtrl'
    })
    .otherwise('/main');
}])

.run(['$rootScope', function($rootScope) {
  $rootScope.eventLog = [];
  $rootScope.$on('$routeChangeSuccess', function(e, curr, prev) {
    // we should see this, and $rootScope.eventLog will get updated
    $rootScope.eventLog.push({
      handler: "Run",
      event: e,
      curr: curr,
      prev: prev
    });
  });
}])

.controller('MainCtrl', ['$scope', '$rootScope',
function($scope, $rootScope) {
  var deregister = $rootScope.$on('$routeChangeSuccess', function() {
    // this won't happen: we'll deregister before the event is called
    $rootScope.eventLog.push({
      handler: "Main",
      event: e,
      curr: curr,
      prev: prev
    });
  });
  
  $scope.$on('$destroy', function() {
    deregister();
  });
}])

.controller('OtherCtrl', ['$scope', '$rootScope',
function($scope, $rootScope) {
  var deregister = $rootScope.$on('$routeChangeSuccess', function() {
    // this won't happen: we'll deregister before the event is called
    $rootScope.eventLog.push({
      handler: "Other",
      event: e,
      curr: curr,
      prev: prev
    });
  });
  
  $scope.$on('$destroy', function() {
    deregister();
  });
}]);