繁体   English   中英

如何从routeChangeSuccess angularjs获取rootScope值

[英]how to get rootScope value from routeChangeSuccess angularjs

我试图按照以下代码从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();

很难说出来,因为您的示例没有显示处理程序的附加位置以及对$rootScope.loggedUser的更改,但是如果它在控制器中发生,则可能不会发生此事件。

直到事件广播之后,控制器才被创建,并且当前视图的控制器将在广播下一个$routeChangeSuccess事件之前被销毁,这意味着如果您要在控制器的目录中注销处理程序,则会错过该事件。 $destroy事件。

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

 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(); }); }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script> <div ng-app="app"> <script type="text/ng-template" id="main.html"> <p>This is the content of the main template</p> <a href="#/other">Other</a> </script> <script type="text/ng-template" id="other.html"> <p>This is the content of the other template</p> <a href="#/main">Main</a> </script> <ul> <li ng-repeat="e in eventLog track by $index"> <h3>{{e.handler}}</h3> <pre>{{e | json:2}}</pre> </li> </ul> <ng-view></ng-view> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM