Note that there are some explanatory texts on larger screens.

plurals
  1. POBroadcasting functions through a service trigger the function multiple times instead of one
    text
    copied!<p>I created a service that shares a confirm modal method, and allow to broadcast methods between controillers.</p> <pre><code>services.SharedService = function($rootScope, $modal) { var sharedService = { controller : '', method : '', args : [] }; sharedService.prepare = function(controller, method){ this.controller = controller; this.method = method; this.broadCast(); }; sharedService.broadCast = function(){ $rootScope.$broadcast('menuBroadcast'); }; return sharedService; }); </code></pre> <p>Then I have three controllers : </p> <pre><code>controllers.ctrl1 = function($scope, $rootScope, SharedService) { $rootScope.$on('menuBroadcast', function() { if (SharedService.controller == 'ctrl1') { $scope[SharedService.method](); } }); $scope.delete = function(){ var c = window.confirm("Are you sure you want to delete it?"); if(c === true){ //delete } }; }; </code></pre> <p>and</p> <pre><code>controllers.ctrl2 = function($scope, $rootScope, SharedService) { $rootScope.$on('menuBroadcast', function() { if (SharedService.controller == 'ctrl1') { $scope[SharedService.method](); } }); $scope.delete = function(){ var c = window.confirm("Are you sure you want to delete it?"); if(c === true){ //delete } }; }; }; controllers.menu = function($scope, SharedService) { $scope.delete1 = function() { console.debug("Calling delete 1"); SharedService.prepare('ctrl1', 'delete'); }; $scope.delete2 = function() { console.debug("Calling delete 2"); SharedService.prepare('ctrl2', 'delete'); }; } </code></pre> <p>The first time I open the confirm from ctrl1, clicking on the ok button works as expected. I can open this modal as many times, it will work.</p> <p>Then, switching to ctrl2, I open the confirm , I have to click two times on the ok button to be able to close the confirm box. </p> <p>The console debugs shows that the "calling delete1" and "calling delete2" are triggered only once. But the console.debug from on("menuBroadcast") is triggered sometimes up to 3 times. Any idea why the service triggers the event more than one time? When injected, is it instantiated more than once?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload