2014-10-28 65 views
1

我有一个页面,其中有一个潜在客户列表,每个客户都可以执行某些操作。每个操作都是一个表单,因此可以在同一页面上多次显示相同的表单。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); 
    }; 

在此先感谢您的帮助。

+0

我不知道这是否是最好的解决方案...我会采取任何更好的答案,但现在我已经通过将当前范围的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

回答

1

基于

每种形式都有它自己的范围和它自身的控制器的实例。

如何我只能把这种对激活控制器

解决方案

如何确定的active controller?如果它像active = true只是使用在偶数听众:

delegateDownLineFormScope.$on('LeadService.DelegatedDownlineSubmitted', (event: ng.IAngularEvent, ajaxResponse: IAjaxResponse) => { 
      if(this.active){ 
      //Do stuff 
      } 
     }); 

另外请注意,我用一个箭头(=>)功能。

+0

工程就像一个魅力,谢谢:-) – juju 2014-10-29 09:05:04