So I have 2 controllers in a module each of them has its own responsibilities, since I am making a real time function so I would need to keep both controller's data in sync if an action is being executed. I've came across angular's $emit
and $on
which it said that I can trigger a function by emitting an event. I've followed the instructions and guidelines on how to implement the triggers but somehow I cannot make it to work.
Basically what I wanted to do is, I have 2 controllers, CtrlA
and CtrlB
. Both of the controllers have many functions say CtrlAactionA
, CtrlAactionB
, CtrlBactionA
, CtrlBactionB
. According to some other guides in stackoverflow, given when CtrlBactionB
in CtrlB
is being called, it should at the same time triggers CtrlAactionB
in CtrlA
but I cannot managed to trigger such action. It will only execute CtrlBactionB
in CtrlB
.
app.controller('CtrlA', function($scope) {
$scope.ctrlAdataA;
$scope.ctrlAdataB = 0;
$scope.ctrlAactionA = function (){
$scope.ctrlAdataA = 'This is the original data.';
}
$scope.ctrlAactionB = function (){
$scope.ctrlAdataA = 'Someone clicked the button in B so I changed!';
$scope.ctrlAdataB++;
}
$scope.$on('buttonClicked', function(event, args) {
$scope.ctrlAactionB();
});
});
app.controller('CtrlB', function($scope) {
$scope.ctrlBdataA;
$scope.ctrlBdataB = 0;
$scope.ctrlBactionA = function (){
$scope.ctrlBdataA = 'I\'ve been clicked!';
$scope.ctrlBdataB++;
$scope.$emit('buttonClicked');
}
});
Here is the plunkr file I made to simulate my described scenario.