Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 868
bsr Avatar asked Dec 05 '22 14:12

bsr


1 Answers

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.

like image 87
Renan Tomal Fernandes Avatar answered Mar 03 '23 12:03

Renan Tomal Fernandes