簡體   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