Listening to multiple events in AngularJS using `$scope.$on`

I am faced with a situation where I need to respond to two different events being transmitted via $scope.$emit and take action only when both have occurred.

For example, if the events are triggered in the following sequence:

$scope.$emit('first');
// do nothing
$scope.$emit('second');
// execute something
$scope.$emit('first');
// Do nothing
$scope.$emit('first');
// Do nothing
$scope.$emit('second');
// execute something

Is there any built-in way to achieve this? Ideally something like

$scope.$on('first', 'second', function() {});

I have considered the following approach:


var triggeredEvents = [];
$scope.$on('first', function() {
    notifyEventTriggered('first');
});

$scope.$on('second', function() {
    notifyEventTriggered('second');
});

function notifyEventTriggered(event) {
    if (triggeredEvents.indexOf(event) == -1) {
         triggeredEvents.push(event);
    }
    if (triggeredEvents.length > 1) {
        execute();
        triggeredEvents.length = 0;
    }
}

Is there a simpler way to accomplish this? Or any suggestions on how to enhance it? Besides creating a service for this purpose.

Thank you

Answer №1

There isn't a direct method to accomplish this task within AngularJS. One approach could be adding a new function to $rootScope like so:

https://example.com/code-sample

var app = angular.module('myApp', []);

app.run(['$rootScope', function($rootScope) {
  $rootScope.onCustomEvents = (function() {

    var trackedEvents = {};    
    return onCustomEvents;

    /*
     * Attach listeners to specified events
     */
    function onCustomEvents(events, callback){
        if(!events || !events.length) return ;

      events.forEach(function(event){
        trackedEvents[event] = false;
        this.$on(event, function(){
            trackedEvents[event] = true;
          evaluateCallback(callback);
        });
      }.bind(this));
    }

    /* 
     * Check if all `trackedEvents` have been triggered. If so, execute the callback and reset the events
     */
    function evaluateCallback(callback){
        var shouldExecute = true;
        for(event in trackedEvents){
        if(trackedEvents.hasOwnProperty(event)){
          if(!trackedEvents[event]){
            executed = false;
          }
        }
      }

      if(shouldExecute){        
        callback();
        for(event in trackedEvents){
          if(trackedEvents.hasOwnProperty(event)){
            trackedEvents[event] = false;
          }
        }
      }
    }
  })();
}]);

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

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

Executing a series of functions in succession using jQuery

I am trying to iterate through an object that contains functions which need to execute consecutively. Ideally, I would like these functions to be chained together in a way where one function waits for the previous one to finish before executing (e.g., func ...

Update the button text dynamically when clicked without using an identifier or a class

If we take a look at my button in the following code: <input type="button" value="BLUE" name="button_blue" /> My goal is to have the value="BLUE" changed to value="RED" or any other desired value when the button is clicked. ...

When I attempt to navigate using a route on my website, all I see is a

Hey everyone, I'm looking to develop a webpage that switches pages using Navbars. I want to utilize bootstrap and react-route-dom to achieve this functionality. However, before incorporating bootstrap, I encountered some errors that went unnoticed. I& ...

Customizing Material UI Components: Implementing the onChange Method

I've been working with the materia kit react template from creative-tim: However, I noticed that the customerInput component in this template lacks an onChange method. Does anyone have a solution for handling user inputs using this specific template? ...

Error: The function `fn` is not defined in objectService in AngularJS using ES6

I am facing an issue with importing a service that extends another service in my controller. The error I am encountering is ng:areq fn is not a function got UserRepository. I suspect the problem lies in how I am injecting this service correctly. Below is t ...

Modal failing to update with latest information

My webpage dynamically loads data from a database and presents it in divs, each with a "View" button that triggers the method onclick="getdetails(this)". This method successfully creates a modal with the corresponding data. function getdetails(par) { ...

Encoding URLs for LoopBack applications

I am experiencing an issue with the filter I have: { "fields": {"goal":true,"amountPledged": true,"title": true},"where": {"title": {"like":`%${this.state.searchText}%`}} } The this.state.searchText value is bio. According to my understanding, it should ...

Tips for incorporating a variable into a JSON object value when dynamically constructing an object

Is there a way to dynamically create an array of objects using a for loop? I have different arrays with values for the key value pairs of these objects. The code snippet I tried is not producing the expected result. var characters = ['Iron Man', ...

Can you please explain the significance of (session?._id)?

export default NextAuth({ ... callbacks: { session: async ({ session, token }) => { if (session?.user) { session.user.id = token.uid; } return session; }, jwt: async ({ user, token }) => { if (user) { ...

Can you highlight the disparities between a factory and a controller?

Currently, I am working on an AngularJs application and recently came across examples of controllers like firebase Auth. .factory("Auth", function($firebaseAuth) { var usersRef = new Firebase("https//<YOUR-FIREBASE-APP>.firebaseio.com/users"); ...

Getting the ID name from a select tag with JavaScript - A quick guide!

Can you help me retrieve the id name using JavaScript when a selection is made in a select tag? I have tried running this code, but it only alerts undefined. For instance, if I select bbb in the select tag, I should be alerted with 2 Any suggestions on ...

Update the image within the svg tag

I am attempting to modify a preexisting SVG element within an HTML document. Here is the current code: <svg class="logo" viewBox="0 0 435 67"> <!-- IMAGE DIMENSIONS --> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo- ...

AngularJS NG-Repeat not iterating multiple times like it should

Can anyone help me with my ng-repeat issue regarding Json data? It seems to only display the second set of dates and not the first. Any insights into why this might be happening? I have tried using a promise, but it is only fetching the information relate ...

Manage image placement using CSS object-position

I have the following code snippet: img{ width: 100%; height: 1000px; object-fit: cover; object-position: left; } <!DOCTYPE html> <html lang="en"> <head> <meta charset ...

What is the best way to connect multiple web pages together?

Hello everyone, I could really use some assistance with a problem I'm facing. As a newcomer to web development, I have a question about navigation bars. I've successfully created a basic webpage with a navigation bar, but now I'm unsure how ...

show image with the help of jquery and ajax

To showcase company information along with an image, I have a controller set up as follows: public JsonResult DisplayCompanyDetails() { CompanyModel cm = new CompanyModel(); string query = "select CompanyName,Address,Conta ...

Angular route is completely unresponsive

I initiated the %a{"ng-click"=>"get_destinations(city)"} Nevertheless, it was supposed to direct me to the "destinations" controller, but that wasn't the case There are no errors in the web console – what could be ...

Distinguishing a button based on its class

I am currently designing a website to showcase personalized store products. Each product info box includes a button, as shown in the screenshot below: https://i.sstatic.net/hiXiY.png Upon clicking on the "Options" button, users can view information about ...

Introducing Vee Validate 3.x and the ValidationFlags data type definition

I'm currently struggling to locate and utilize the ValidationFlags type within Vee-Validate 3. Despite my efforts, I am encountering difficulties in importing it. I am aware that this type is present in the source code located here. However, when I a ...