angularjs - Fetching an object from a service which hasn't yet been created -
folks:
i have 2 controllers, ctrla , ctrlb - both unrelated each other within same page.
ctrla
queries end point , returns json object tags
, passed service method myservice.savetags(tags)
store object.
ctrlb
needs populate $scope variable $scope.tags
fetching tags
object created via ctrla
.
the service:
.factory('myservice', function($http, $q, $window) { var myservicefactory = {}; var savedtags = {}; // ..other methods.. myservicefactory.savetags = function(tags) { if(!savedtags.tags){ console.log('saving tags..'); savedtags.tags = tags; } }; myservicefactory.getsavedtags = function() { console.log('returning tags..'); return savedtags.tags; }; return myservicefactory; })
this issue appears ctrlb
gets called first, when $scope.savedtags = myservice.getsavedtags();
runs, returns undefined.
question: angular n00b here - best way fetch tags after ctrla
has populated object?
you can use watch on getsavedtags
service method inside ctrlb
know when populated. like
$scope.$watch(function() { return myservice.getsavedtags() },function(newvalue) { if(newvalue) { $scope.savedtags = newvalue; } });