I've been struggling to figure out how to facilitate communication between components. The primary question that has stumped me is: when should I opt for $watch versus $on ($broadcast/$emit) to establish component communication?
I've identified three fundamental scenarios:
Controller + Directive. These components naturally communicate using $scope bidibinding. By placing a service containing shared state in the $scope through an object (
$scope.filter = {}
), a sensible approach can be achieved.Controller + Controller. Utilizing Dependency Injection (DI) to inject singleton services with encapsulated state for inter-controller communication. Services are linked to directives following the previous method, providing data binding effortlessly.
Directive + Directive. This particular scenario remains a puzzle for me. There are directives residing in different scopes and some sharing the same scope, each requiring distinct functionality like updating all changes (e.g., slider + charts) or triggering HTTP requests (e.g., select input).
Therefore, here are the inquiries:
- When deciding between $watch or $on ($broadcast/$emit) for component communication, what factors should I consider?
- In directive-to-directive communication, should I lean towards utilizing $watch?
- Alternatively, should I prefer using $broadcast in a directive-to-directive scenario?
- Is it more favorable to share state through injection+binding or injection+events?