AngularJS - Cannot access RootScope

2019-07-06 05:02发布

问题:

Strange problem, I cannot access the $rootScope in CtrlB variable that is getting set in CtrlA.

HTML:

<div role="main" class="container_9" ng-controller="CountryCtrl" ng-init="updateToken('<?php echo $TOKEN; ?>')">  

CtrlA

app.controller('CountryCtrl', function ($scope,$rootScope, $http) {
  $scope.updateToken = function(token) {
        $rootScope.token = token;
  } 
});  

CtrlB

app.controller('DealerListCtrl', function ($scope, $http, $rootScope, dealerService) {
  $scope.dealer = [];
    $http.get('files/framework/dealer/'+ $rootScope.token).success(function(data) {
        $scope.dealerall = data;
    });
  //$scope.dealerall = dealerService.api.get({token: $scope.token});
  $scope.orderProp = 'name';

});  

Error Message:

/framework/dealer/undefined 500 (Internal Server Error)   

What am I doing wrong?

UPDATE
Plunker Code:
http://plnkr.co/edit/r559zyMKjA64xSdmrTem

It's not capable to run...

回答1:

It's accessing the $rootScope just fine. If it wasn't you'd be getting a javascript error about $rootScope not being defined. Instead, it's tacking "undefined" onto the end of the request URL, meaning $rootScope.token is undefined. Do whatever you need to to make sure $rootScope.token is defined.

I suspect CtrlB is getting called before CtrlA, and so $rootScope.token hasn't been set yet.



回答2:

There are two key problems here: first, you are using $rootScope when you should be using a service, and second, you are assuming the order of execution of the controllers. If it was just a matter of the second, you could set up $watch commands to monitor changes to ensure your second controller had an updated value, whenever it was set.

But you shouldn't pollute the global scope. Wrap your token into a service that can be injected and on which you can $watch for changes. That said, I can't post anything more specific (i.e. code) without knowing in what context your controllers run.

But I hope this helps! Update your post with more info if you want and I'll dive a little deeper. Actually, it'd be great if you could create a Plunker or jsFiddle that I can directly modify.