我有一个页面,其中有一个潜在客户列表,每个客户都可以执行某些操作。每个操作都是一个表单,因此可以在同一页面上多次显示相同的表单。AngularJs - 向单个控制器发送广播事件
每个表单都有自己的范围,它是控制器自己的实例。当表单被提交时,我调用一个服务来完成ajax操作,完成后我广播一条消息,并在控制器中收听消息。问题是因为表单的每个实例都有自己的控制器实例,所以每个表单都会触发偶数侦听器。我如何才能将此称为主动控制器?下面是一些sampel代码:
服务:
/**
* Delegate downline submit
*/
delegatedDownlineSubmit(delegateDownLineModel: IDelegateDownLineModel) {
this.PostJson('/api/Lead/DelegateDownLine', delegateDownLineModel)
.success(function (response: IAjaxResponse) {
if (response !== null) {
LeadServices.rootScope.$broadcast('LeadService.DelegatedDownlineSubmitted', response);
}
});
}
控制器 - 形式的每个实例调用一次:
delegateDownLineFormScope.$on('LeadService.DelegatedDownlineSubmitted', function (event: ng.IAngularEvent, ajaxResponse: IAjaxResponse) {
//Do stuff
});
我也打过电话广播只在范围:
LeadServices.rootScope.BroadcastToElement('#Lead_123 form[name=DelegateDownLineForm]', 'LeadService.DelegatedDownlineSubmitted', response);
/**
* Broadcast a message to another element on the page
*/
scope.BroadcastToElement = function (selector: any, message: string, ...args: any[]) {
var broadcastArgs = [message];
if (args) {
broadcastArgs = broadcastArgs.concat(args);
}
return angular.element(selector).scope().$broadcast.apply(this, broadcastArgs);
};
在此先感谢您的帮助。
我不知道这是否是最好的解决方案...我会采取任何更好的答案,但现在我已经通过将当前范围的id作为额外参数(例如, leadService.delegatedDownlineSubmit(delegateDownLineFormScope.DelegateDownLineModel,delegateDownLineFormScope。$ id); 然后使用该额外参数进行广播: LeadServices.rootScope。$ broadcast('LeadService.DelegatedDownlineSubmitted'+ scopeId,response); 最后: delegateDownLineFormScope。$ on('LeadService.DelegatedDownlineSubmitted'+ delegateDownLineFormScope。$ id etc – juju 2014-10-28 16:31:26