AKA AKA - 1 day ago 5
AngularJS Question

Call a controller function of one module from controller of another module in angularjs

There is a scope function which in triggered in module A by ng-click. Now I want to call this scope function through another module B. I am using $broadcast and $on but it is executing two time and not working properly. But when I use a button in module A and call that scope function it is working.
I need the call to this function from module B.

Answer

Add this as a dependency in both your controllers

.factory('messageService',
function () {
  var messageService = {};
  var listeners = {};
  var count = 0;
  messageService.registerListener = function (listener) {
    listeners[count] = listener;
    count++;
    return (function (currentCount) {
      return function () {
        delete listeners[currentCount];
      };
    })(count);
  };
  messageService.broadcastMessage = function (message) {
    var keys = Object.keys(listeners);
    for (var i = 0; i < keys.length; i++) {
      listeners[keys[i]](message);
    }
  };
  return messageService;
})

in your controller A

messageService.broadcastMessage(...)

in your controller B

function callBackFunction(){
  ...
}
messageService.registerListener(callBackFunction)

original answer

Comments