Mikhail
Mikhail

Reputation: 769

What is the best way to call callback in child scope?

I have a page that loads some data by multiple http requests, then afterwards I have to do some logic in several directives inside of this page.
I'd like to ask, what is the best pratice for this kind of situations?
Right now I have a boolean flag, that indicates that content been loaded. The first idea was to use timeout in these directives to check each second if the content is loaded, and execute this logic if it does.
The second idea was to use the broadcasting. I like this idea, but since those directives has closure scopes, as far as I get, I have to broadcast on the $rootScope. And as far as I understand, this is not the best idea in the terms of productivity.
So please, let me know what is the best solution for this kind of task.

Upvotes: 1

Views: 70

Answers (2)

David Votrubec
David Votrubec

Reputation: 4156

You can use the $q service for this. Specifically it's $q.all() method

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

The advantage is that is is "Angular native" so do not need to worry about synchronization with $scope etc

Upvotes: 0

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

$rootScope.emit() is the best approach for angular1. This is the built in pubsub pattern

$rootscope.emit() is not expensive as the broadcast method since the broadcast percolates down all the scopes

Just use emit in controller

$rootScope.$emit('topic');

in directive

$rootScope.$on('topic', function(){})

Upvotes: 3

Related Questions