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
so, in controller I get the data through
//myService.setName(); //mented 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.
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(); //mented 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.
2 Answers
Reset to default 16The 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.
- make
$scope.name = myService.getName
and use it as an functionHello {{name()}}
. - make
myService.getName()
return an object like{ real_name: "foo" }
and usename.real_name
on the view - bind
myService
to the scope and direct use thegetName
function$scope.myService = myService;
and on viewsmyService.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:
- Inject the $http service into the new service
- Define the getName() function that the view is calling
- Pass the $scope in to the setName() function and change the value on the $scope
http://plnkr.co/edit/6SkzXK