3

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
  • Your Plunker is quite long. Can you simplify it a skosh to make it easier to play with? Commented Jan 9, 2013 at 6:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, thanks. See update in my first post. I'm very new to AngularJS. Maybe there's a possibility to optimize my app.js
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.