user3689167 user3689167 - 5 months ago 150
AngularJS Question

angular js, broadcast an event and wait for it to complete

I have a an angular event like this:

$rootScope.$broadcast("postData");
doSomething();


however, doSomething() must wait for postData to complete before execution.
I would normally do something like:

$rootScope.$broadcast("postData").then(function(){
doSomething();
});


But apparently this isn't a thing in angular...Any ideas?

Answer

You could $broadcast the event, listen for it in your other controller with $on, and $emit another event on completion, and listen for it in your original controller so you know when it is finished.

I would not recommend this approach. Instead use a service.

Emit and broadcast are coupling your mechanisms for communication to the view because the $scope is fundamentally a fabric for data-binding.

The services approach is far more maintainable and can communicate between services in addition to controllers.

Comments