nourdine
nourdine

Reputation: 7597

What is the preferred way to make different parts of an angularjs app talk to each other?

I was wondering what is the preferred way to make different part of an app interact with each other.

For instance let's say we have a directive A that display a product in the shopping basket of a user. This directive has access to a persistence service that allows CRUD operations on the item.

Let's also say we have a directive B that displays a general message.

Now the user decides to delete a product from his basket. Is it acceptable to make it publish an event this way?:

 $scope.$emit("item-deleted");

and then have B listening on that type of event:

$scope.$on("data-received", function(event, next, current) {
  // show up and tell "item deleted succesfully"       
}); 

Is it a good way to achieve the result? It definitely is in other frameworks and in UI development in general. I was just wondring if it is a viable way in angular.

Thanks

Upvotes: 0

Views: 37

Answers (2)

khanmizan
khanmizan

Reputation: 936

create a service for directive B which will provide data for general messages. inject that service into the underlying service of directive A. then call that service with proper message.

Directive A should auto display this data, because of 2 way data binding of angularjs.

Upvotes: 0

prbaron
prbaron

Reputation: 867

You should use services instead of events propagation. With the dependency injection, it is really easy to use. It is the best way to make two controllers to talk to each other.

More on services : https://docs.angularjs.org/guide/services

Upvotes: 1

Related Questions