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.
$scope.name = myService.getName
and use it as an function Hello {{name()}}
.myService.getName()
return an object like { real_name: "foo" }
and use name.real_name
on the viewmyService
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With