AngularJS - updating scope value with asynchronous response

I am trying to share some data between AngularJS controllers. Also I get the data through http request. When I access the data from controller, it is null and later (if manually refresh through UI), the data is available. I am guessing the issue is very similar to here But whatever I tried in my case didn't work. Please see the fiddle

http://plnkr.co/edit/6SkzXK?p=preview

so, in controller I get the data through

//myService.setName(); //commented as it breaks the code

which sets the value in service and access through getName()

it most likely could be solved through, $rootScope.$apply , as in the above link but I couldn't make it work.

The problems is that when your controller is initialized, you copy the result of getName() to a variable $scope.name = myService.getName(). Since $scope.name is holding a string and not a reference it will not be updated when getName() changes.

There are 3 ways to resolve this.

  1. make $scope.name = myService.getName and use it as an function Hello {{name()}}.
  2. make myService.getName() return an object like { real_name: "foo" } and use name.real_name on the view
  3. bind myService to the scope and direct use the getName function $scope.myService = myService;and on views myService.getName()

I prefer the first, given is more clear. The second is good when you have more data. The third isn't a good way in my opnion.

There are three things you need to do to get your plunker to work:

  1. Inject the $http service into the new service
  2. Define the getName() function that the view is calling
  3. Pass the $scope in to the setName() function and change the value on the $scope

http://plnkr.co/edit/6SkzXK