0

Currently my test setup is as such:

app.run(function($rootScope, $http, $location) {
url = $location.path() + '/raw';
$rootScope.test = 'hi';
$http.get(url).success(function(data) {
    $rootScope.test = data.personality;
    console.log($rootScope.test);//A
});})

app.controller("Big5", function ($scope, $http, $location, $rootScope) {
  console.log($rootScope.test);}//B

The console.log at //A works as intended - it logs the JSON from the url. However, the console.log at //B just returns 'hi', the initial $rootscope.test variable. Any way to fix this?

I should mention that the page where this is needed calls the controller to render a graph.

LLai
  • 13,128
  • 3
  • 41
  • 45
skywang329
  • 49
  • 5

1 Answers1

1

The reason why the value at B is logged as 'hi' is that this in the value at the point of executing the controller function. In order to set the value using the result of HTTP service call, you should call this from within the controller function. i.e

app.controller("Big5", function($rootScope, $http){
   $http.get(url).success(function(data) {
      $rootScope.test = data.personality;          
   })
}

More generally it's bad practice to use root scope, I suggest using the $scope service instead :)

GRex
  • 21
  • 1
  • Ah yes - this was how I implemented on the first try; however, I have many controllers that create multiple graphs from the data received from this http call; as such, placing an http call into every controller would result in many calls to get essentially the same data (later parsed). The API from which I am calling this data from has a cost per call, so having one central call would be preferred. – skywang329 Jul 02 '17 at 14:59