Transfer the $rootScope parameter to a named function within the factory

I'm currently working on an application that has been highly modularized. Within this app, there is a factory responsible for sending notifications to a controller from another module. To accomplish this, I am utilizing the $rootScope object to trigger an event called newNotification and pass along the necessary data.

Everything is functioning as expected with the code provided below:

notifications.factory.js

(function() {
    'use strict';

    function notificationsFactory($rootScope) {
        return {
            sendNotification: function(data) {
                switch(data.type) {
                    case 'actors':
                        $rootScope.$broadcast('newNotification', data);
                        break;
                    .....
                }
            } 
        }
    };

    angular.module('features.notifications.factory', [])
    .factory('notificationsFactory', ['$rootScope', notificationsFactory]);
})();

However, I would like to create a cleaner factory by returning an object with named functions since more functions will be added in the future. Essentially, I want it to look something like this:

notifications.factory.js

(function() {
    'use strict';

    function notificationsFactory($rootScope) {
        return {
            sendNotification: sendNotification
        }
    };

    function sendNotification(data) {
        switch(data.type) {
            case 'actors':
                $rootScope.$broadcast('newNotification', data);
                break;
            ....
        }
    };

    angular.module('features.notifications.factory', [])
    .factory('notificationsFactory', ['$rootScope', notificationsFactory]);
})();

The issue arises when the $rootScope object is not defined within the sendNotification function, which is understandable. I am currently struggling to find a solution to this problem.

I have searched online for a potential solution, but expressing the complexity of the issue without incorporating some code makes it challenging. Hence, my post requesting assistance.

Thank you for your help and understanding :)

Answer №1

When opting for a service over a factory, you have the ability to transfer injected dependencies using this. Utilizing a service in this manner becomes even more convenient when leveraging ES6 classes, and helps in preparing you slightly more for Angular 2.0.

(function() {
    'use strict';

    function NotificationsService($rootScope) {
        this.$rootScope = $rootScope;
    };

    NotificationsService.prototype.sendNotification = function sendNotification(data) {
        switch(data.type) {
            case 'actors':
                this.$rootScope.$broadcast('newNotification', data);
                break;
            ....
        }
    };

    angular.module('features.notifications.service', [])
    .service('NotificationsService', ['$rootScope', NotificationsService]);
})();

ES6 Version:

(function() {
    'use strict';

    class NotificationsService {
        constructor($rootScope) {
            this.$rootScope = $rootScope;
        }

        sendNotification(data) {
            switch(data.type) {
                case 'actors':
                    this.$rootScope.$broadcast('newNotification', data);
                    break;
                ....
            }
        }
    }

    angular.module('features.notifications.service', [])
    .service('NotificationsService', ['$rootScope', NotificationsService]);
})();

Answer №2

Implement the sendAlert-method within your alertsFactory- factory:

function alertsFactory($rootScope) {
    function sendAlert(message) {
        switch(message.level) {
            case 'error':
                $rootScope.$broadcast('newAlert', message);
                break;
            ....
        }
      };
      return {
          sendAlert: sendAlert
      }
    };

Alternatively, you can use a service instead of a factory and structure it like this:

function alertsFactory($rootScope) {
    this.sendAlert = function(message) {
        switch(message.level) {
            case 'error':
                $rootScope.$broadcast('newAlert', message);
                break;
            ....
        }
      };
    };

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

Encountered a glitch while trying to install React JS using npx create-react-app xyz

After entering the command in the terminal, I encountered an error stating: npm Err! code-ENOENT npm Err! syscall lstat npm Err! path Interestingly, this same command worked perfectly on my instructor's laptops. For reference, I have attached a snaps ...

Exclude a specific link from a JQuery function

Check out this unique single page site that utilizes a waypoint script for navigation and highlighting nav items - The functionality works seamlessly, however, we are facing an issue where we need to modify a link to redirect to an external website. Unfor ...

Arranging arrays in Javascript within two dimensions

In my data set, I possess an array that contains tags along with their respective counts. tags_array[0] = tags; tags_array[1] = tags_count; My goal is to rearrange the arrays based on the tag counts to easily identify the most popular tags. ...

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

I'm looking to extract the values of input fields from a specific form that I have just clicked on. Each form and their input fields share the same class, but each input field contains

When working with a PHP while loop that generates multiple forms with the same id and classes, it can be challenging to target specific input values. Each form input has its own distinct value, but clicking on the submit button of a particular form shoul ...

Is there a way to determine if a parent of my HTML element possesses a CSS class?

Looking at this HTML code snippet - <div id="parent" class="foo"> <div id="child"> </div> </div> Is there a way to create a test to verify if the child element is utilizing the foo class? I attempted: element .children("#chi ...

I have successfully integrated my custom external JavaScript code with React Router, and everything is working

Assistance Needed! I am working on a project that consists of 4 pages, one of which is the About page. I am using react-router to manage the paths and contents between these pages through their respective links. import React from 'react'; impo ...

The head.js feature similar to "Modernizr" does not recognize ms-edge

It has come to my attention that the head.js script is unable to detect the Microsoft "Edge" browser correctly. In addition, it erroneously adds classes like chrome and chrome55 to the <html> element. Is there a better way to handle this issue? The ...

Manipulate Images Efficiently with jQuery

Are there any jQuery plugins or JavaScript controls available that can display an array of images, with the option to delete an image based on user action? For example, something similar to this: , but with a dedicated delete button on each image. One ad ...

Having trouble executing partial views with node.js and AngularJS?

I have been working on my AngularJS application and everything functions correctly when I browse it. However, I've encountered an issue while trying to configure Express. The main page displays fine, but when I click on the hyperlinks to load partial ...

Acquiring a document using angularjs

My goal is to provide users with the option to either open or save a file when they click on its name: <a href data-ng-click="getFile(file.id)"> {{file.name}}</span> </a> This action triggers a method ...

Unable to show JSON data on the console

I am attempting to retrieve a large array of JSON objects from a remote server. The server-side is based on Node.js + redis. Here is my ajax query: $.ajax({ crossDomain: true, type:"GET", contentType: "application/json", url: "http://****. ...

What is the process for uploading a file in the Fat-Free framework?

Can someone help me with uploading a file in the Fat Free Framework using AngularJS? I want to send a POST request at Fat Free Framework. The file should have an extension of .jpg, be limited to 2mb in size, and only allow for 4 files to be uploaded. Pleas ...

You can only set headers once during the initial request; any additional attempts to set headers will result in an

I encountered a specific issue with the error message "Can't set headers after they are sent". Here is the relevant code snippet: create: (request, response, next) -> socket = @app.socket # # This method will be used to call the right method ins ...

Azure Chatbot that logs conversations in Webchat whenever the user selects 'none of the above' option

Recently, I've delved into the world of web chat services and embarked on a journey to craft a chat bot using pure JavaScript code that can seamlessly integrate into any HTML file. Despite consulting Microsoft's documentation, I find myself in a ...

angular.js is throwing an error message stating that it has encountered an unknown provider causing an issue

I've been encountering this specific error repeatedly and I'm unable to pinpoint the cause: angular.js:13708 Error: [$injector:unpr] Unknown provider: fstackProvider <- fstack <- MainController Here is a snippet from my config.js file: a ...

Cleanse the email using express-validator, but only if it is recognized as an email format; otherwise, disregard

Currently, I am developing an API that requires users to input their username and password for authentication purposes (login functionality). Users have the option to enter their email, username, or mobile number. To ensure consistency, I need to normalize ...

Unable to forward to another page using NodeJS (Express)

After spending a considerable amount of time trying to find a solution, I finally managed to create a simple button click redirection using NodeJS and Express. However, when clicking on the "Next page" button in my index.html file, I encountered an error s ...

When the child of li is clicked instead

Below is a list I have: <ul id="orderlist"> <li id="2"> <span class="pull-right value">Ready</span> <img src="" class="img-responsive"> Filet Mignon <small>2 servings</small> <small ...

Is it possible to input text outside of a UL tag?

I am currently exploring the capabilities of framework7 and I have a question regarding placing an input type="text" outside the UL tag. Despite my attempts, the CSS styles are not being applied to the text input field. Any insights on this issue would be ...