0

I am trying to trigger an event from a parent controller and the child controller should listen to it.Using angular's event framework there are two ways to go

Method 1

parentcontroller

$scope.$broadcast("eventToChild");

childController

$scope.$on("eventToChild",function({console.log("received event");})

Method 2

parentcontroller

$rootScope.$emit("eventToChild");

childController

$rootScope.$on("eventToChild",function({console.log("received event");})

I understand that $rootscope.$emit will only invoke listeners on $rootscope and we can stop the propagation of the event using event.stopPropagation(),given this fact how can $scope.$broadcast be a better solution than $rootScope.$emit.

Which one among these two is a better solution and why?

Divya MV
  • 2,021
  • 3
  • 31
  • 55
  • Have a detailed look here as well :http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/ – Tharif Jul 01 '15 at 05:48
  • @utility if all of you see the question marked as duplicate here i have given the link to todmotto's explanation of $rootScope.$emit and $rootScope.$broadcast.This question came to my mind after reading the blog post and the question which is marked as the original of this question.I wish you have spend some time to understand what i am really asking for – Divya MV Jul 01 '15 at 06:00
  • thank you @Divya toddmotto link was not the duplicate one ,SO post was duplicate one.that toddmotto link was posted just to put some light on the question. – Tharif Jul 01 '15 at 06:02
  • before even posting this question i had gone through the SO question and had given the toddmotto link there.After reading the answer to this SO question i tried out it and this question arised. – Divya MV Jul 01 '15 at 06:03

2 Answers2

0

There's no better performance differences between them. But the difference is just of it's usage.

$broadcast is used for broadcasting event to downwards and $emit is used for emitting the event upwards.

Next thing, you're wrong at saying $emit works only with $rootScope. It works with $scope too.

For more information about them see differences here.

Community
  • 1
  • 1
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

They just work in a different way.

Broadcast goes from the element downards, to whoever is trying to catch an event; in the case of rootscope, every single scope is below it, thus everyone can catch it and treat it; While emit is the way of a child scope to go up. Usually, if you want to trigger the event in a condition/scope parameters that are related to the parent, you'll use broadcast - while if you want to use it with those of the child, you'll use emit.

A. Abramov
  • 1,823
  • 17
  • 45