Broadcast and listen to events in AngularJS using `$rootScope.$emit`

I am currently working on a large Angular app and I have encountered the need to trigger an event using $rootscope.$emit, and then listen to this event inside a factory. Doing this inside a controller is not feasible because the controller hasn't loaded yet when initializing the User.

Although the code works fine, I am curious if there is a better way to achieve this.

The first factory that emits the event:

angular
.module('app.core')
.factory('AuthenticationService', ['$rootScope', 'requestHttpService', AuthenticationService])

    function AuthenticationService($rootScope, requestHttpService) {
        var isLoggedIn = false;
        return {
            logIn: logIn
        }
        function logIn(action) {
            return requestHttpService.runOpenRequest(action)
                    .then(logInComplete)
                    .catch(logInError);

            function logInComplete(userData) {
                $rootScope.$emit('initUser', userData);
            }

            function logInError(error) {
                console.log('Something went wrong:  ' + error);
            }
        }
    };

And the second factory that listens to the event:

angular
   .module('app.user')
   .factory('manageUser', ['$rootScope', manageUserFactory]);

    function manageUserFactory($rootScope) {
        var user = {'id': '', 'name': ''};
        $rootScope.$on('initUser', function (event, userData) {
            initUser(userData);
        });

        return {
            initUser: initUser
        }

        function initUser(userData) {
           user = {'id': userData.id, 'name': userData.name};
        }
    };

Answer №1

Avoid using events in this scenario is my recommendation.

Since you are utilizing $emit and it moves up the scope hierarchy, including the current scope where it is emitted, and in this case $rootScope is already at the highest level. Therefore, it will only be used to notify events bound to $rootScope.

I suggest directly calling the factory method by injecting it like so: instead of

$rootScope.$emit('initUser', userData);
use manageUser.initUser(); after injecting the manageUser factory into the AuthenticationService.

Events should be avoided due to their performance implications.

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

AngularJS- issue with button visibility on 'toolbar' widget

In my angularJS application, there is a page with multiple widgets displayed. When a user clicks on the 'Settings' button on the page (separate from the widgets), a toolbar for each widget appears showing different buttons depending on the widget ...

Is there a way in Angular 1.5 to compile the HTML of a parent component from within a child component?

I have created two angular components called app-menuitem and app-menu. The app-menu component contains a list of app-menuitems as its children, without using transclude. App-menuitem Component: angular.module('app') .component('appMen ...

Developing 'Drop Down' Views in AngularJS

With AngularJS, I have successfully rendered a table containing a list of items with unique IDs for each row. Now, my goal is to create a pull-down view that allows users to see detailed information about each row. This pull-down view will include a nested ...

Using AngularJS to Retrieve Data

Encountering an error in the console and unable to fetch data from MySQL. Looking for suggestions on resolving the following issue: Utilized AngularJS, PHP, MySQL, and MaterializeCSS Error: $http.get(...).success is not a function Below is the code sn ...

Assistance required in translating Firebase syntax from version 7.15.1 to version 9.6.1

I'm embarking on my Firebase journey and trying to follow a tutorial that seems to be a bit outdated. I could use some assistance in updating the code to match the newer version, as it appears the syntax has changed. The tutorial uses Firebase 7.15.1, ...

Dynamic Data Transfer from UI-Router State to Remote Controller Using AngularJS

Answer Found: Check Below I have an illustration along with the actual PLUNKER CODE HERE I have successfully made dynamic changes to the left menu and corresponding view, but my code is not very sophisticated. I realized it may not work if I upgrade to U ...

Display dynamic content in a div using ajax and add animation effects, along with a "back" button functionality

I am in the process of creating a fantasy NFL web app using bootstrap and jQuery. Initially, I opted for Framework7 due to its user-friendly native app interface but decided to shift towards building a fully responsive page instead. Within my project, the ...

Finding a specific document in MongoDB using a unique slug within Next.js: A step-by-step guide

I have a collection of data in MongoDB structured like this: [ { "Post": "this is a post", "_id": ObjectId("630f3c32c1a580642a9ff4a0"), "slug": "this-is-a-title", "title" ...

Tutorial on integrating jquery ui's '.droppable' feature with the jQuery '.on' method

I have a main div with three inner divs labeled 1, 2, and 3 as shown below: <div id="main"> <div style="height:30px; background-color:yellow;" class="bnr">Banner</div> <div style="height:30px; background-color:yellow;" class=" ...

Tips for accessing a web service using JavaScript (AJAX)

I have two projects: one is a web service and the other is an ASP.NET web project. I am trying to insert data using JSON (with AJAX). I tested the web service file with code behind and it works fine, but I'm encountering an error with the JavaScript ...

Darken the entire webpage and gradually fade in a specific div element using Jquery

Currently, I am working on implementing the following functionality: - When a link is clicked, it should trigger a function to show a DIV (#page-cover) that will dim down the entire background. This div has a z-index of 999. - Following the dimming effect, ...

Serialize the elements within an array using JSON.stringify

I'm trying to convert an object into a string, but for some reason it's not working correctly: function httpRequest(url) { this.url = url; this.headers = []; } var req = new httpRequest("http://test.com"); req.headers["cookie"] = "version=1 ...

Adding the data from an ajax object response to an array

I'm encountering an issue where my Ajax response is not being properly looped through each object and pushed into the array. I've been stuck on this problem for quite some time now. The Ajax response looks like this... {type:'blog_post&apo ...

Ensuring the accuracy of query parameters in REST api calls using node.js

Each object type in the GET request to the API has a set of valid query parameters. var queryFields = { 'organisation': ['limit', 'page', 'id', 'search'], 'actor': ['limit', 'p ...

Updating a single AngularJS model within an ng-repeat loop following an HTTP request

I have a code snippet for my application that retrieves data from an http source. Here is the initial JSON data: "phasen": { "item1": false, "item2": [{ "phasen_id": "1", "phasen_group_id": "2", "phasen_group_name": "group ...

Is it false to say that false in Javascript is still false?

After conducting some research, it appears that the question I have in mind has not been asked before, or maybe it has slipped under my radar. A rational approach would be to consider the following logic: false && false === true false && true === false t ...

Retrieve a single element from each array stored in MongoDB

Can someone help me with a query in MongoDB? I have a document structure like this, and I am looking to utilize the $addToSet operator to add a value to one of the items within the 'votes' field. However, I also need to remove that value from all ...

What is the best way to divide a single object in an array into multiple separate objects?

In my dataset, each object within the array has a fixedValue property that contains category and total values which are fixed. However, other keys such as "Col 2", "Col 3", etc. can have random values with arbitrary names like "FERFVCEEF erfe". My goal is ...

Detecting changes to DOM elements without using jQueryResponding to DOM element

Suppose I have the following HTML structure: <div id='content'></div> I want to receive an alert when there are height mutations on this element. I thought about using the MutationObserver class for this, but I encountered a specifi ...

failure of svg spinning

I'm currently working with an SVG file and attempting to incorporate a spinning animation similar to loaders and spinners. However, I am facing an issue where the rotating radius is too large and I am struggling to control it effectively. CSS: .image ...