35

I want to execute a function inside a directive, whenever there is a state change in the parent scope.

The obvious way to achieve this is to use event broadcasts ($broadcast) and listeners ($on).

I am curious if using a $watch is an alternative to event broadcast. If it is, how do the two compare?

As far as I understand, the expression to be watched is evaluated every $digest cycle. So are events more efficient than watch?

Yogesh Mangaj
  • 3,200
  • 6
  • 32
  • 45
  • possible duplicate of [What is 'cheaper' performance-wise $broadcast or $watch](http://stackoverflow.com/questions/19616520/what-is-cheaper-performance-wise-broadcast-or-watch) – Blackhole May 09 '14 at 09:46

1 Answers1

33

The $watch function is used to watch variables on the scope. Scope inheritance allows you to watch parent scope variables as well, so that is definitely the way to go for your use case. As you correctly said, $on is used to watch for events, which you can $broadcast to child scopes or $emit to parent scopes. This gives you much more control, but it might cause more mistakes while coding, since you could get an update to a scope variable from a point which you don't monitor and forget to notify the listeners.

You can still use events when you don't inherit scope variables. But be careful not to pollute a large scope, using services might be an option there, because you immediately see whether it is injected or not.

Since a directive gets the scope it is on (or inherits from it), I would say $watch is a much cleaner option here.

If you want to have an isolated scope on your directive, you can pass arguments as attributes and $observe them.

Ferdinand Torggler
  • 1,304
  • 10
  • 11
  • That's a very clear explanation, but I missed the point here- "But be careful not to pollute a large scope", do you mean not to pollute with too many events? – Yogesh Mangaj May 09 '14 at 12:51
  • 1
    When you communicate between completely independent controllers/directives via events, they both have to have a common parent scope which you are broadcasting on. In most cases this will be the $rootScope. In a large application, you will end up with many events on the rootscope and you will lose control over which component subscribes to which event, whereas with dependency injection (and services for communication) you can see it immmediately, and it is way easier to test/debug. – Ferdinand Torggler May 09 '14 at 13:14
  • 4
    As long as you keep tight control, via Services, of your broadcast event -- which should be best practice anyway -- I'd argue the performance savings over watches outweigh everything else. At least on pages where there is a non-trivial amount of $watches (explicit or implicit). At minimum you should do a watch count chk to see which camp you fall in. – user1821052 Nov 26 '14 at 19:32