AngularJs-向单个控制器广播事件

AngularJs - Broadcast event to single controller

本文关键字:广播 事件 控制器 单个 AngularJs-      更新时间:2023-09-26

我有一个页面,其中有一个Lead列表,每个Lead都可以执行某些操作。每个操作都是一个表单,因此同一表单可以在同一页面上多次显示。

每种形式都有它自己的范围和它;自己的控制器实例。提交表单时,我调用一个服务来执行ajax操作,完成后我广播一条消息,并在控制器中收听该消息。问题是,表单的每个实例都有自己的控制器实例,每个表单都会触发偶数侦听器。我怎么能只为活动控制器调用它?这是一些样本代码:

服务:

/**
    * 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);
    };

提前感谢您的帮助。

基于

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

我怎么能只为主动控制器调用这个

解决方案

如何确定active controller?如果它类似于active = true,请在偶数侦听器中使用它:

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

另外请注意,我使用的是箭头(=>)函数。