AngularJS - Sending event to a specific controller

I am facing an issue with my page where a list of Leads each have specific actions that are represented by forms. These forms can be displayed multiple times on the same page. Each form has its own scope and controller instance. After submitting a form, an ajax operation is performed via a service, and a message is broadcasted upon completion. However, the problem arises when the event listener is fired for every form instance. How can I ensure that the event is only triggered for the active controller? Here is a snippet of the code:

The service:

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

Controller - triggered for each form instance:

delegateDownLineFormScope.$on('LeadService.DelegatedDownlineSubmitted', function (event: ng.IAngularEvent, ajaxResponse: IAjaxResponse) {
            //Do stuff
        });

I have also attempted to broadcast the message only on the scope:

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

Any assistance on resolving this issue would be greatly appreciated. Thank you.

Answer №1

Scope and Controller

Every form operates within its own scope and has a separate instance of the controller.

Furthermore

Is there a way to specifically call this for the currently active controller?

Resolution

How can you identify the active controller? If it is based on a condition like active = true, then you can simply utilize that in the event listener:

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

It is important to note that an arrow function (=>) is being used here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

Passing data through Angular2 router: a comprehensive guide

I am currently developing a web application with the latest version of Angular (Angular v2.0.0). In my app, I have a sub-navigation and I want to pass data to a sub-page that loads its own component through the router-outlet. According to Angular 2 docume ...

I'm looking to configure @types for a third-party React JavaScript module in order to use it with TypeScript and bundle it with webpack. How can I accomplish this?

Imagine you have a third-party npm package called @foo that is all Javascript and has a module named bar. Within your TypeScript .tsx file, you want to use the React component @foo/bar/X. However, when you attempt to import X from '@foo/bar/X', y ...

Clearing all data in a form upon opening

Within a single portlet, I have organized two forms under separate tabs. What I am aiming for is that whenever I switch to tab 2, all fields within its associated form should automatically be cleared without the need for a button click. Even after attempti ...

Storing individual socket.io data for each client

Is there a proper way to save data on Socket.io per client? I was considering using this approach, but after doing some research, it seems like it may not be the best method: io.on('connection', function(socket) { console.log('socket co ...

Transition your Sequelize migrations to TypeORM

I'm currently in the process of transitioning a Node.js application from vanilla JS to Nest.js. In our previous setup, we used Sequelize as our ORM, but now we've decided to switch to TypeORM for its improved type safety. While exploring the Type ...

There seems to be an issue with the import class for React PropTypes. The prop

I have multiple oversized items that are utilized in numerous components, so I created a PropTypes file for each item. For example: PropTypes/PropLargeObject.js This file contains: import PropTypes from "prop-types"; const PropLargeObject = Prop ...

Animation for maximum height with transition from a set value to no maximum height

While experimenting with CSS-transitions, I encountered an unusual issue when adding a transition for max-height from a specific value (e.g. 14px) to none. Surprisingly, there is no animation at all; the hidden elements simply appear and disappear instant ...

Generate a .py file through an HTML button click and save it to your device

My current project involves developing HTML and JavaScript code for a chatbot. I need to implement a feature where, upon receiving a Python program from the chatbot, a download button should be displayed. When users click on this Download button, they shou ...

I'm encountering an error in TestCafe that says "TypeError: Cannot read properties of undefined (reading 'match')". Which specific segment of my code is causing this issue?

retrieveUrlFromEmailData(emailData:any){ const emailContent = emailData.email_text; const urlPattern = /(https?:\/\/[^\n]*)/; const foundUrl = emailContent.match(urlPattern)[0]; return foundUrl } ...

Why is the body the last element in Angular modules arrays?

I have a question regarding architectural practices. When defining an Angular module, one common approach is to do it like this: angular.module('app', []) .controller('Ctrl', ['$scope', function Ctrl($scope) { //body.. ...

What is the best way to retrieve the source code generated by Ajax

I designed a PHP script that generates text dynamically and returns it with a unique div id. However, when I use Ajax to retrieve this text as responseText, I am unable to access the properties of the div using JavaScript because the new text is not added ...

Numerous column pictures that occupy the entire browser screen

I am looking to create a grid of clickable images that expand to cover the width of the browser window without any space on either side. Ideally, I would like each image to be 180x180px in size, but if it's easier they can resize based on the browser ...

Leverage Vue's ability to inject content from one component to another is a

I am currently customizing my admin dashboard (Core-UI) to suit my specific needs. Within this customization, I have an "aside" component where I aim to load MonitorAside.vue whenever the page switches to the Monitor section (done using vue-router). Here ...

Is it necessary to uncheck the row checkbox when inputs are left empty after blurred?

Two issues have cropped up here. When clicking on an input within a row, the corresponding checkbox should be checked. Currently, only the first text input is able to check the checkbox due to the use of .prev(). Is there a different approach that can be t ...

Creating a dynamic form where input fields and their values update based on user input in jQuery

In my form, I have an input field where users will enter an ISBN number. Based on the input number, I need to populate two other input fields: one for book title and one for author name. I am currently calling a JavaScript function on the onblur event of ...

Likelihood of triggering a function based on percentage

Hey everyone, I'm looking to add some randomness to the buttons on my website. I have a Button that could activate function one, function two or function three. However, I want to make it so there is a 60% chance that function one gets called from the ...

When using AngularJS, an array variable within a div tag is cloned and duplicated across all other div tags

The array ar in the first #div1 is replicated in all the other div elements. Even after trying different variable names, all divs still share the same array variable name ar. <body ng-app=""> <div id="div1" ng-init="ar=['java',&ap ...

Tips for adjusting the duration of a background in jQuery

jQuery(document).ready(function(){ jQuery('div').css('background-color','#ffffff').delay(12000).css('background-color','#000000'); }); Hello everyone! I'm having some trouble with this code. I am ...

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...