1

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.

Kenny Yap
  • 1,317
  • 5
  • 17
  • 39

2 Answers2

1

Since you are trying to implement events, you have to use $broadcast instead of $emit, and you have to do it from parent scope (i.e. $rootScope), since $broadcast dispatches events downwards. So in the CtrlB controller change this line:$scope.$emit('buttonClicked'); with this one: $rootScope.$broadcast('buttonClicked');, and add $rootScope as a dependency in your CtrlB controller.

Here's a plunker with the change implemented

plunkr

The $emit wasn't working because $emit dispatches an event upwards, and it couldn't find the CtrlA there. More info: AngularJS Emit

Saulo Lozano
  • 256
  • 2
  • 6
0

I found this related to your issue: https://stackoverflow.com/a/19468749/5235299

Hope it ll help you a bit

Community
  • 1
  • 1
slou
  • 34
  • 1
  • 6