What's the correct way to communicate between controllers?
I'm currently using a horrible fudge involving window
:
function StockSubgroupCtrl($scope, $http) {
$scope.subgroups = [];
$scope.handleSubgroupsLoaded = function(data, status) {
$scope.subgroups = data;
}
$scope.fetch = function(prod_grp) {
$http.get('/api/stock/groups/' + prod_grp + '/subgroups/').success($scope.handleSubgroupsLoaded);
}
window.fetchStockSubgroups = $scope.fetch;
}
function StockGroupCtrl($scope, $http) {
...
$scope.select = function(prod_grp) {
$scope.selectedGroup = prod_grp;
window.fetchStockSubgroups(prod_grp);
}
}
You should use the Service , because
$rootscope
is access from whole Application , and it increases the load, or youc use the rootparams if your data is not more.I will create a service and use notification.
As at any point Notification Service is singleton it should be able to provide persisted data across.
Hope this helps
Regarding the original code - it appears you want to share data between scopes. To share either Data or State between $scope the docs suggest using a service:
Ref: Angular Docs link here
This is how I do it with Factory / Services and simple dependency injection (DI).
Using get and set methods within a service you can passing messages between controllers very easily.
in HTML HTML you can check like this
I liked the way how
$rootscope.emit
was used to achieve intercommunication. I suggest the clean and performance effective solution without polluting global space.