Reputation: 4541
I have an Angular service that gets some properties set from an asynchronous call. By the time this call completes, controllers that reference these properties have already gotten their values from the service. My current solution is to call $rootScope.$broadcast in the service and handle that event in my controller to update the properties.
Service Code:
this.modelInfo = resultFromAsyncCall;
$rootScope.$broadcast('settingsApplied');
Controller Code:
$scope.modelInfo = MyService.modelInfo;//Service hasn't recieved async response yet.
$scope.$on('settingsApplied', function(event, args){
$scope.modelInfo = MyService.modelInfo;
});
My question is: Is there a cleaner way to update dependent controllers when a service is updated than broadcasting/catching events?
Upvotes: 0
Views: 39
Reputation: 621
Use a promise (preferred) or a $watch.
Promise
Code in controller:
MyService.GetModelInfo.then(function(result) {
$scope.modelInfo = result;
});
Watch
Code in controller:
$scope.$watch(function() {
return MyService.modelInfo
}, function(newValue, oldValue) {
if (newValue) {
$scope.modelInfo = newValue;
}
});
Upvotes: 1