I'm familiar with the following methods to implement communication between controllers.
Are there others? Are there better approaches / best practices?
$broadcast
/$emit
.controller("Parent", function($scope){
$scope.$broadcast("SomethingHappened", {..});
$scope.$on("SomethingElseHappened", function(e, d){..});
})
.controller("Child", functions($scope){
$scope.$broadcast("SomethingElseHappened", {..});
$scope.$on("SomethingHappened", function(e, d){..});
})
.controller("AnotherChild", functions($scope){
$scope.$on("SomethingHappened", function(e, d){..});
});
or, from the View:
<button ng-click="$broadcast('SomethingHappened', data)">Do Something</button>
Advantages:
Disadvantages:
$rootScope
, is used<div ng-controller="Parent">
<div ng-controller="Child">
<div ng-controller="ChildOfChild">
<button ng-click="someParentFunctionInScope()">Do</button>
</div>
</div>
</div>
or, in code
.controller("ChildOfChild", function($scope){
$scope.someParentFunctionInScope();
});
Advantages:
Disadvantages:
$rootScope
, is used$watch
Controllers only react to change in scope-exposed data and never call functions.
.controller("Parent", function($scope){
$scope.VM = {a: "a", b: "b"};
$scope.$watch("VM.a", function(newVal, oldVal){
// react
});
}
Advantages:
ng-repeat
Disadvantages:
$rootScope
As Samuel said, using a service to sharing data is a recommended method. The idea is that the state of the data are maintained consistently, regardless of any controller. This two articles can give you an idea of "how to" and "why": Sharing Data Between Controllers, The state of angularjs controllers.
I use functionality-specific shared services to communicate between controllers.
You can create a generic shared service to have a central point to subscribe to and broadcast events, but I find functionality-specific services to be easier to maintain over time, especially as the project and team grows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With