3

Why I use scope.$parent().$emit() other than scope.$emit() is when the directive use scope:true and there's one more directive use scope:true, and they are placed at same DOM node.

Then scope.$emit() will emit event to the other directive too and can be catch as same as parent scope. But scope.$parent().$emit() will only emit event to parent. Is it good to use scope.$parent().$emit()?

It seems not matter whether other directives can catch the event or not, but I'm not sure about this.So maybe ONLY emit to parent can be good at some case.
Here's a example plunk

"second-directive" event can only be catch by MainCtrl. but "second-directive-two" can be catch by MainCtrl and first directive.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
tjfdfs
  • 729
  • 10
  • 26

2 Answers2

6

Here is related question: How to stop $broadcast events in AngularJS?

You can use

$rootScope.$broadcast('second-directive-two', 'from second');

instead of

$scope.$parent().$emit('second-directive-two', 'from second');

and cancel event handling in controller

$scope.$on('second-directive-two',function(event,args){
    event.preventDefault();
});

And don't handle event 'second-directive-two' in first directive if event has been prevented

$scope.$on('second-directive-two',function(event,args){
    if (!event.defaultPrevented) {
        // do useful job
    }
});

Here is plunk

Update:

Why it isn't good practice ?

In this case you are tied to structure of DOM hierarchy. Imagine that you have to move directive First to partial and include it via ng-include. Scope hierarchy has been changed. $scope.$parent().$emit() doesn't work since this moment. And you spent time to fix this problem.

Generally $scope.$parent().$emit() generate potentially problem code

Community
  • 1
  • 1
Anton Rodin
  • 991
  • 2
  • 12
  • 19
  • this seems good. But I'll appreciate if you can explain why use `$scope.$parent().$emit()` is not good. Thanks:) – tjfdfs Nov 13 '13 at 01:25
0

It sound like you could use scope.$broadcast() instead of emit. It is like emit but the data bubbles the other way around in the scope chain.

TheHippo
  • 61,720
  • 15
  • 75
  • 100
  • Is $broadcast only broadcast downstream to child scope only? How child scope can use broadcast to broadcast event to parent scope? – tjfdfs Nov 12 '13 at 09:37
  • I test it. And using `scope.$broadcast()` can be catch by directive only. – tjfdfs Nov 12 '13 at 09:57