Is it possible to generate multiple services from a single factory in Angular?

Recently, I developed a service called tableService using the following code:

app.factory('tableService', [function() {
   var data = some data;

   var foo = function (){
      //do something to data here
   };

   return {
      data: data,
      foo: foo
   }
}]);

Now, I am looking to create another service that mirrors the properties of tableService so that I can leverage its functionality with a different dataset.

Is there a way I can achieve this without duplicating the code for each service by doing something like:

app.factory('tableService', 'secondService', [function() {


}]);

This would help streamline the process and avoid repeating code unnecessarily. Any suggestions?

Answer №1

To utilize a local object definition, simply create a new instance from it using the method getInstance.

 app.factory('tableService', [function() {
   var data = some information;

   MyService(){
       // code ...
       this.data = data;
   }

   MyService.prototype.bar = function(){
       // code ...
   }


   function newInstance(){
       return new MyService();
   }


   return {
      getInstance: newInstance,
   }
}]);

How to create instances :

var tableInstanceA = tableService.getInstance();
var tableInstanceB = tableService.getInstance();

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

Switch between Fixed and Relative positions as you scroll

Just a small adjustment is needed to get it working... I need to toggle between fixed and relative positioning. JSFiddle Link $(window).on('scroll', function() { ($(window).scrollTop() > 50) ? ($('.me').addClass('fix ...

Creating a dynamic trio of graphs with HTML5, CSS3, and Vanilla JavaScript

I successfully created a tree graph using HTML5 and CSS3, but currently the nodes are static. I am looking to enhance the graph by making it dynamic. By dynamic, I mean that if the number of nodes increases or there are multiple children added, the graph ...

Customizing React components based on API data

const LinkList = () => { const [links, setLinks] = useState([]); const url = 'http://localhost:5000/xyz'; const hook = () => { console.log('effect'); axios .get(url) .then(respo ...

The onClick event handler fails to trigger in React

Original Source: https://gist.github.com/Schachte/a95efbf7be0c4524d1e9ac2d7e12161c An onClick event is attached to a button. It used to work with an old modal but now, with a new modal, it does not trigger. The problematic line seems to be: <button cla ...

Tips for updating multiple documents in a MongoDB database using an array of values

I have a range of Product items in my inventory and when a client places an Order, they submit an array of objects. Each object in the array includes the _id product (objectId) and the quantity they purchased. [ {producId: "dshsdsdh72382377923", quantity: ...

Struggling to integrate buttons into an h2 element with the use of createElement() and appendChild() in HTML/CSS/JS

As I work on developing a website, one of the features I've been implementing is the ability for users to add books to a list and then review or delete them. The process was smooth sailing until I reached the point of adding buttons for these actions. ...

Unlocking the potential of AngularJS: A guide to using factories effectively across

I created a factory function to provide specific options for all name fields and I am looking to globally utilize or invoke that factory in the application. How can I achieve this global usage? Below is the code snippet I have written: checks.factory(&ap ...

Greetings: Obtaining an array of text within the <td> tags

Here is the HTML Source: <td bgcolor="#ffffbb" colspan=2><font face="Verdana" size=1>2644-3/4<br>QPSK<br><font color="darkgreen">&nbsp;&nbsp;301</font> - 4864</td> I am looking to extract text array wit ...

Learn how to implement data-binding in AngularJS using the ui-router and ControllerAs syntax, all without the

I have been following the guidelines laid out by John Papa, but I am facing difficulty in binding values from child controllers to parent controllers using ui-router, ControllerAs, and vm variables instead of $scope. In my attempts, I created two example ...

Unable to update values in Google Sheets using the node.js API

I have been working on a node.js project that involves extracting the location of a cell based on a person's name and date. While I am able to determine this information easily, I encounter difficulties when trying to update the cell using the .update ...

A function that can retrieve distinct values for a specific property within an array of objects while maintaining their original order

Here is some information I have: $scope.Reports = [ { Id: 1, Name: 'Report One', Year: 2016, Month: 5 }, { Id: 2, Name: 'Report Core', Year: 2016, Month: 5 }, { Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 }, { I ...

When it comes to entering text in a text input or textarea within a large module in Vue.js, taking

While filling out my large form, I noticed a delay in rendering whenever I typed quickly into the input boxes. <b-form-input v-model="paymentItems.tierStepUPYear" type="text"></b-form-input> ...

The list in Jquery UI Autocomplete is not updating correctly

Currently, I am using jQuery UI Autocomplete in conjunction with WebSockets to fetch and display a list of options. Each time a keystroke is detected on the input field (.keyup()), a call is made to retrieve the list. However, I have encountered an issue w ...

Having trouble getting Angular ngIf to work in combination with Razor syntax?

I'm currently working with Angular Js and Razor. @{ var pageMode = (string) ViewBag.PageMode; } <div ng-if="@pageMode == 'answer'"> <h2>Greetings</h2> </div> Even though the value in ViewBag.PageMode is "ans ...

What is the process for defining the host in a websocket connection?

When working on my page, I establish a websocket connection to the server using ws://127.0.0.1:5000/ws in development and ws://www.mymachine.com/ws when deployed to production. Is there a more efficient way to handle this so that I don't have to manua ...

Weaknesses found in the React Js library bundled with create-react-app

Each time I initiate a new react project using npx create-react-app <AppName>, the following vulnerabilities are detected: 96 vulnerabilities found - Packages audited: 1682 Severity: 65 Moderate | 30 High | 1 Critical Node Version: v14.18.1 Npm: 7.20 ...

Angular: synchronously updating scope using data fetched asynchronously from a factory

What is the best way to accomplish this task? 1. factory.updater = function(varObjToBeUpdated){ $http.post('/url', {}) .success(function(data){ for (data_field in data) varObjToBeUpdated[data_field] = data[data_field ...

unable to reset contact form functionality

I need to implement a Contact Us form on my website. The form should clear the text fields after submission and display a Thank You message. Below is the HTML code: <div class="form"> <div id="sendmessage">Your message has been sent. Thank yo ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

Could somebody clarify the situation with the `push` function?

Something seems off with the behavior of the push method. Instead of pushing to only one index within the forEach, it appears to be pushing to all three indexes. Can anyone see what might be causing this unexpected result? let arrayToReduce = [ [ 1, 2, ...