通过服务的广播功能多次触发该功能而不是一次

时间:2013-12-02 00:02:29

标签: javascript angularjs modal-dialog angular-ui

我创建了一个共享确认模态方法的服务,并允许在控制器之间广播方法。

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;

});

然后我有三个控制器:

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
    }
  };
};

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');
    };
}

我第一次从ctrl1打开确认时,点击“确定”按钮按预期工作。我可以多次打开这个模态,它会起作用。

然后,切换到ctrl2,我打开确认,我必须在ok按钮上单击两次才能关闭确认框。

控制台调试显示“调用delete1”和“调用delete2”仅触发一次。但是来自on(“menuBroadcast”)的console.debug有时会被触发3次。知道为什么服务会多次触发事件吗?注入时,是否会多次实例化?

1 个答案:

答案 0 :(得分:0)

重复

How can I unregister a broadcast event to rootscope in AngularJS?

控制器不止一次实例化。我必须在调用$ destroy时在侦听器上取消注册$ rootScope。$。

var cleanUpFunc = $rootScope.$on('menuBroadcast', function {
    if (SharedService.controller == 'ctrl1') {
       $scope[SharedService.method]();
    }
});

$scope.$on('$destroy', function() {
    cleanUpFunc();
});