Javascript 通过服务的广播功能会多次触发该功能,而不是一次
我创建了一个共享确认模式方法的服务,并允许在控制器之间广播方法Javascript 通过服务的广播功能会多次触发该功能,而不是一次,javascript,angularjs,modal-dialog,angular-ui,Javascript,Angularjs,Modal Dialog,Angular Ui,我创建了一个共享确认模式方法的服务,并允许在控制器之间广播方法 services.SharedService = function($rootScope, $modal) { var sharedService = { controller : '', method : '', args : [] }; sharedService.prepare = function(controller, method){ this.controller = cont
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
}
};
};
及
第一次从ctrl1打开确认时,单击ok按钮按预期工作。我可以多次打开此模式,它将工作
然后,切换到ctrl2,我打开确认,我必须点击ok按钮两次才能关闭确认框
控制台调试显示“调用delete1”和“调用delete2”仅触发一次。但console.debug from on(“menuBroadcast”)有时会被触发3次。知道为什么服务会多次触发事件吗?注入时,是否多次实例化?重复
控制器被实例化多次。调用$destroy时,我必须在侦听器上取消注册$rootScope.$
var cleanUpFunc = $rootScope.$on('menuBroadcast', function {
if (SharedService.controller == 'ctrl1') {
$scope[SharedService.method]();
}
});
$scope.$on('$destroy', function() {
cleanUpFunc();
});
我一直在用window.confirm()测试它,同样的情况也发生了。因此,这个问题与$modal无关。更详细地说,每次我访问使用ctrl1的页面时,ctrl1都会被重新实例化。ctrl2也是如此。假设我访问了ctrl1的页面5次。$on()将被激发5次,因为ctrl1的5个实例被实例化。这似乎不是我所期望的行为。有什么想法吗?
var cleanUpFunc = $rootScope.$on('menuBroadcast', function {
if (SharedService.controller == 'ctrl1') {
$scope[SharedService.method]();
}
});
$scope.$on('$destroy', function() {
cleanUpFunc();
});