0

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.

PriyankaChauhan
  • 953
  • 11
  • 26
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • use a service instead https://docs.angularjs.org/guide/services – EmptyCup Dec 01 '16 at 11:50
  • How can i call a controller function from a service? – Ankit Agarwal Dec 01 '16 at 11:53
  • https://codedump.io/share/iDilTj9GKGnV/1/global-communication-in-angular-module-event-bus-or-mediator-patternservice read up – EmptyCup Dec 01 '16 at 11:58
  • If you still have difficulties let me know, I'll type a sample snippet. – EmptyCup Dec 01 '16 at 11:59
  • The controller function which i want to call manipulates several scope variables which is not possible in service. The link you gave states the sharing data between controllers but i need to call a controller of another module that manipulates its own scope variables. – Ankit Agarwal Dec 01 '16 at 12:02
  • When a button in Module A is clicked a controller function of Module B is executed., I have achieved this, but the problem is that my $on on module B is executed two times. The function is module B is however executed but doesn't show intended results. – Ankit Agarwal Dec 01 '16 at 12:04
  • controller A has a function A and controller B has a function B, you want function B to call function A, correct? – EmptyCup Dec 01 '16 at 12:04
  • But controller A and controller B is in different modules – Ankit Agarwal Dec 01 '16 at 12:05
  • $broadcast and $on works but $on is called twice and the function in controller B actually sets a value for ng-repeat which is not being set when i do this. – Ankit Agarwal Dec 01 '16 at 12:07
  • These both controllers are of directives controller in different modules – Ankit Agarwal Dec 01 '16 at 12:08

1 Answers1

1

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

Community
  • 1
  • 1
EmptyCup
  • 421
  • 4
  • 14