What\'s the correct way to communicate between controllers?
I\'m currently using a horrible fudge involving window
:
function StockSubgro
Since defineProperty has browser compatibility issue, I think we can think about using a service.
angular.module('myservice', [], function($provide) {
$provide.factory('msgBus', ['$rootScope', function($rootScope) {
var msgBus = {};
msgBus.emitMsg = function(msg) {
$rootScope.$emit(msg);
};
msgBus.onMsg = function(msg, scope, func) {
var unbind = $rootScope.$on(msg, func);
scope.$on('$destroy', unbind);
};
return msgBus;
}]);
});
and use it in controller like this:
controller 1
function($scope, msgBus) {
$scope.sendmsg = function() {
msgBus.emitMsg('somemsg')
}
}
controller 2
function($scope, msgBus) {
msgBus.onMsg('somemsg', $scope, function() {
// your logic
});
}
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
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.
Actually using emit and broadcast is inefficient because the event bubbles up and down the scope hierarchy which can easily degrade into performance bottlement for a complex application.
I would suggest to use a service. Here is how I recently implemented it in one of my projects - https://gist.github.com/3384419.
Basic idea - register a pubsub/event bus as a service. Then inject that eventbus where ever you need to subscribe or publish events/topics.
function mySrvc() {
var callback = function() {
}
return {
onSaveClick: function(fn) {
callback = fn;
},
fireSaveClick: function(data) {
callback(data);
}
}
}
function controllerA($scope, mySrvc) {
mySrvc.onSaveClick(function(data) {
console.log(data)
})
}
function controllerB($scope, mySrvc) {
mySrvc.fireSaveClick(data);
}
You can do it by using angular events that is $emit and $broadcast. As per our knowledge this is the best, efficient and effective way.
First we call a function from one controller.
var myApp = angular.module('sample', []);
myApp.controller('firstCtrl', function($scope) {
$scope.sum = function() {
$scope.$emit('sumTwoNumber', [1, 2]);
};
});
myApp.controller('secondCtrl', function($scope) {
$scope.$on('sumTwoNumber', function(e, data) {
var sum = 0;
for (var a = 0; a < data.length; a++) {
sum = sum + data[a];
}
console.log('event working', sum);
});
});
You can also use $rootScope in place of $scope. Use your controller accordingly.