Guide on building a Dynamic factory in AngularJS

For my project, I need to implement a dynamic factory in AngularJS with a unique name. Here is an example of what I am trying to achieve:

  function createDynamicFactory(modId) {
     return myModule.factory(modId + '-existingService', function (existingService) {
        return existingService(modId);
    }); 
}

Although I am aiming to generate a new factory with a dynamic name when calling this function, it is unfortunately not functioning as expected. How can I accomplish this task? Furthermore, how can I dynamically inject it into my controller or directive?

Answer №1

If you need to enhance your service generator, consider annotating it in this manner. The process involves taking the module and extension, then adding an annotation for a dependency on the "echo" service (a sample service created for echoing text and logging it to the console), enabling the generated service to utilize it:

enhanceService = function(module, identifier) {
    module.factory(identifier+'-service', ['echo', function(echo) {
            return {
                run: function(msg) {
                    return echo.echo(identifier + ": " + msg);
                }
            };
        }]);
    };

You can proceed by creating a number of dynamic services:

enhanceService(app, 'ex1');
enhanceService(app, 'ex2');

For injection, there are two approaches. If you have a known convention, you can pass it along with the annotation like ext1 is demonstrated. Otherwise, retrieve an instance of the $injector and obtain it that way.

app.controller("myController", ['ex1-service', 
                                '$injector',
                                '$scope',
                                function(service, $injector, $scope) {
    $scope.service1 = service.run('injected.');   
    $scope.service2 = $injector.get('ex2-service').run('dynamically injected');
}]);

To see the complete functioning demo, visit this fiddle: http://jsfiddle.net/jeremylikness/QM52v/1/

Update: To dynamically create the service post initialization of the module, a few tweaks are necessary. Instead of attempting to register the module, just return an annotated array. The dependencies come first in the parameters, followed by the registration function:

enhanceService = function(identifier) {
    return ['echo', function(echo) {
        console.log("in service factory");
            return {
                run: function(msg) {
                    return echo.echo(identifier + ": " + msg);
                }
            };
        }];
    };

Then, obtain a reference to the array and invoke instantiate on the $injector to set up the wiring with dependencies:

var fn = enhanceService('ex2');
$scope.service2 = $injector.instantiate(fn).run('dynamically injected');

Check out the fiddle for this version here: http://jsfiddle.net/jeremylikness/G98JD/2/

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

What is the best way to store a downloaded video from the server?

I am currently in the process of downloading a video from a server using JavaScript XHR (specifically Angular $http GET with response type 'blob'). My question is, how can I save this downloaded video to a Chrome application's local storage ...

Accessing a precise div element in a webpage

Currently, I am utilizing Vue.js and Nuxt for my web development. One issue I am facing is related to anchors. Specifically, when I navigate to mysite.com/page1#section1, I want the page to scroll to section1. In my code, I have the following snippet: < ...

Open the window by using the `Window.open` method, then find and

Is there a way to open a document, not in a new window but on the same page using JavaScript.Window.Open()? Could it be possible to display the document within a specific div element that is obtained with getElementById? For example: document.getElementB ...

Utilizing Vue.js for Tabs in Laravel 5.8

I am encountering an issue in Laravel while attempting to set up a Vue instance for tabs. Currently, only Tab 1 and Tab 2 are displayed without any content, and the tabs themselves are not clickable links. Could this problem be related to how I am calling ...

Sorting data in Javascript can be done efficiently by utilizing the .filter method

Can someone help me identify what I might be doing incorrectly? I have a chained filter under computed that is giving me an error message stating 'product.topic.sort' is not a function. My intention is to use 'select' to provide sortin ...

Interact with an external JavaScript function using a button within a web application

I have a JavaScript file called dmreboot_service.js in my /js folder. By running this file with the command node /js/dmreboot_service.js, it successfully triggers a direct method in Azure. My goal is to be able to run this function or file when a button o ...

A step-by-step guide on changing the class of a focused contenteditable element with a button click using jQuery

I need assistance changing the class of an element within a contenteditable div. Here is my current code: <button>swap class</button> <div contenteditable="true"> <h1 class="line-height-1">Your Headline Here</h1> </di ...

"Enhance your website with dynamic uploader forms and AJAX scripts - Railscast #383 shows you

I've successfully implemented the uploader functionality from Railscast #383, but I'm wondering if it's possible to dynamically add and remove the uploader link using ajax? Additionally, I'd need to include the "service" instance id wh ...

What is the reason for AngularJS not utilizing the most recently assigned value?

<html> <head> <title>Test</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="angul ...

Storing information in an array with automatic ID generation_incrementing

Here is an array in a specific format, however, there is no "ID" field available when the form is submitted. The requirement is to have an auto-generated ID assigned and saved in a JSON Array upon user submission of the form. With each form submission, t ...

What is causing the error when trying to parse a JSON with multiple properties?

Snippet: let data = JSON.parse('{"name":"dibya","company":"wipro"}'); Error Message : An error occurred while trying to parse the JSON data. The console displays "Uncaught SyntaxError: Unexpected end of JSON input" at line 1, character 6. ...

In the Opera browser, the closing script tags seem to mysteriously vanish

I recently built a website using bootstrap and implemented the JQuery load function to merge separate HTML files into one for better organization. The site is currently live on github pages. However, I've encountered an issue specifically with Opera ...

Is there a way to avoid waiting for both observables to arrive and utilize the data from just one observable within the switchmap function?

The code snippet provided below aims to immediately render the student list without waiting for the second observable. However, once the second observable is received, it should verify that the student is not enrolled in all courses before enabling the but ...

Implement a Selection Feature in Angular

Currently, I am working on an application where users can add new rows with the same fields. One of the requirements is to allow users to add an option to a select element. While I have successfully implemented this in jQuery, I am facing challenges integr ...

Activate SVG graphics upon entering the window (scroll)

Can anyone assist me with a challenging issue? I have numerous SVG graphics on certain pages of my website that start playing when the page loads. However, since many of them are located below the fold, I would like them to only begin playing (and play onc ...

What is causing my Vue leave transition to malfunction?

Currently, I am utilizing vee validate for my form validation. Specifically, I have implemented vue transition to handle the display of validation errors in the following manner: <input type="text" name="name" v-validate="'required'"> < ...

Creating a flowchart of a finite state machine within a browser-based software platform

If you're curious about the core logic behind my application, check out this link for a great explanation: Code Golf: Finite-state machine! I plan to implement this logic to create finite state machines on my web app using a library. I've been ...

How can I specify the array's length when using JSON.stringify in AngularJS?

I am looking to store form values in JSON to send via $http.post. One of the values, rooms, should be an array with a length determined by the selected value from md-select. The value of Adult should be included within each room entry. var data = { rooms: ...

Creating multiple React applications using shared configuration files: A step-by-step guide

I am in the process of developing a React app, and my goal is to create multiple React apps that share the same configurations - including modules and configuration files like tailwind.config.cjs. How can I modify my environment to achieve this? My plan i ...

*ngIf doesn't seem to be functioning as expected compared to other *ngIf directives

Encountering a peculiar issue with my *ngIf related to the isAdmin variable which determines whether the list of users in userList should be displayed or not. Strangely, it seems to behave differently compared to other *ngIf statements within the same comp ...