Creating an AngularJS factory class that allows for the creation of multiple instances through the use of the

As a newcomer to AngularJS, I have created a factory class to generate instances of my "Case" class. However, I'm facing an issue where creating new instances of "Case" seems to affect my existing instances as well. Despite being simple, I can't seem to solve this problem.

I thought I was being clever by designing a basic (generic) class.

Here's my factory class:

.factory('Case', function($q, $http) {
  var optionsProto = {
    id : null,
    reference : "",
    fields : []
  }

  var self = this;

  return function Case(options) {
    angular.extend(self, optionsProto, options);
    return self;

    // Updates via. webservice, if possible
    this.update = function get(options) {
      // not implemented yet
      return self;
    };

    // Saves via. webservice, if possible
    this.save = function save() {
      // not implemented yet
      return self;
    };
  }
})

And here's my controller:

.controller('CasesCtrl', function($scope, Case) {

  $scope.cases = [
    new Case({"id": 1}),
    new Case({"id": 2}),
    new Case({"id": 3}),
  ];

  console.log($scope.cases);

})

The console output appears as follows:

Object {id: 3}
Object {id: 3}
Object {id: 3}

Answer №1

Ensure you are selecting the correct this. Here is an example:

.factory('Case', function($q, $http) {
  var optionsProto = {
    id : null,
    reference : "",
    fields : []
  }; 

  return function Case(options) {
    angular.extend(this, optionsProto, options);

    // Update via webservice, if possible
    this.update = function get(options) {
      // not implemented yet
      return this;
    };

    // Save via webservice, if possible
    this.save = function save() {
      // not implemented yet
      return this;
    };
  }
});

If you wish to maintain the self variable (to bind all functions to the Case object), use:

  return function Case(options) {
    var self = this;
    angular.extend(self, optionsProto, options);

    // Update via webservice, if possible
    this.update = function get(options) {
      // not implemented yet
      return self;
    };

    // Save via webservice, if possible
    this.save = function save() {
      // not implemented yet
      return self;
    };
  }

Additionally, note that I have removed the return self; line. This is because new statements automatically return the created object, causing interruption in the function.

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

Angular7 & Electron: Resolving the Issue of Loading Local Resources

I am encountering difficulties while working with electron. Although I can successfully load my project using ng serve, I encounter an error when attempting to open it with electron as shown in the developer tools Not allowed to load local resource: fil ...

Error in header file redefinition - C++

I have a scenario where I've defined template functions in a header file within a namespace. Interestingly, when I include this header in two separate source files within the same project, no redefinition error occurs. /* template.h */ namespace x { ...

Encountering the error message "The getStaticPaths function in Next.js requires the 'id' parameter to be provided as a string"

Having an issue with the getStaticPaths function. Every time I attempt to create a dynamic display using a parameter, it gives me an error message: A required parameter (id) was not provided as a string in getStaticPaths for / movies / [id]. However, if ...

Display the items in the shopping cart along with the quantity of each item

Here is the array response I received from my API regarding the user's cart: [ { id: 13, user_id: 13, product_id: 8, product_name: 'Lenovo Ideapad Intel Celeron 1TB HDD 8GB RAM Win 1' }, { id: 14, user_id: 13, ...

How can a static website incorporate a local image without the need for backend functionality?

I have a unique challenge with my static website. It is designed to display a local image from the user's computer without utilizing a traditional backend system. The website itself is hosted on a static file server, and all image processing must be d ...

What makes the obj loader incompatible with the mtl loader in Three.js?

I am encountering an issue while loading models using three.js. I have an obj file with mtl and a glb model of the same object. When I load the model with the obj and the mtl loader, the object is not displayed in the browser. If I only load it with the ob ...

Angular Offline App Failing to Function Properly in Offline Mode

Our Single Page HTML5 offline app utilizes AngularJS, Breeze, and ASP.NET MVC to store all files in the cache for seamless offline use. A manifest file lists all the necessary files, including Angular templates, which are loaded using standard Angular rout ...

What is the best way to set up a horizontal navigation system on a webpage?

Below is the code for a horizontal page dragging navigation system inspired by www.blacknegative.com. In this system, users can click and drag left or right to navigate through different pages. The current setup allows for four pages, but I need to expand ...

Encountering an error when using Angular Material virtual scroll in conjunction with Angular-UI

Trying to incorporate Angular material's virtual scroll feature on angular-ui-tree is proving to be a bit challenging. The error message that keeps popping up is: Controller 'uiTree', which is required by directive 'uiTreeNode', ...

Issue with SharePoint Rest API search query functionality

Hey there! I'm currently facing issues with calling the Sharepoint Rest API for a search query. I can't seem to figure out why it's not working. Additionally, I'm unsure if my URL input is correct. Below is the code snippet I've w ...

In search of an effective solution for effortlessly executing Protractor automations on autopilot

As a quality assurance professional, I develop my automation scripts using Protractor, which is perfectly suited for working with AngularJS. Currently, I manually execute the automation tests by simply clicking "Run" in the software. However, I am interest ...

How can I restrict validation to trigger only when a field loses focus?

Is there a way to validate the input tag for time format 00:00:00 after exiting the field, rather than during user typing? Any suggestions on how to accomplish this? <label for="operativeToTime">Operative to time</label> <input name ...

Common issues when attempting to extrude shapes with three.js

As I embark on my journey with three.js, I am encountering challenges when it comes to extruding certain 2D shapes. Currently, I am working with a GeoJSON file that includes data on all the counties in the US. Using d3.js along with a d3.geo.albersUSa() pr ...

Issue with modal-embedded React text input not functioning properly

I have designed a custom modal that displays a child element function MyModal({ children, setShow, }: { children: JSX.Element; setShow: (data: boolean) => void; }) { return ( <div className="absolute top-0 w-full h-screen fle ...

The callback within the Q.all promise is never executed

I am a bit confused about the functioning of `Q.all`. Below is a code snippet I have written (jsfiddle): function callUrl(remoteEndPoint){ return $.ajax({ url: remoteEndPoint, method: "GET", dataType: "json", contentType: "application/js ...

Creating a personalized ESLint rule specifically for Redux reducers

Currently working with Redux and Redux Toolkit alongside ESLint presents a challenge. Sometimes, when adding my extraReducers, I find that I do not need both the state and action properties provided by Redux. As a result, ESLint throws an error in these c ...

What steps can I take to ensure that my React child components will render successfully, even if a prop is absent

TLDR; Seeking solution to render child components in React even if a property of this.props is missing. My React app utilizes Yahoo's Fluxible and fetches data from a Wordpress site using WP REST API. Sometimes, the API may return incomplete data cau ...

Issue encountered while sending binary data to the server

After attempting to read a local file on the client side and sending it to the server, I encountered an error while trying to retrieve the image. JavaScript let req let rsp async function _post(url,data) { req = await fetch(url,{method: 'POST' ...

Show an xeditable form that can be edited within a popup window

Looking for a way to enclose the editable form within a bootstrap uib-popover-template. Tried the editable ui-bootstrap popover method, but encountering unexpected issues. Check out Plunker 1 --> https://plnkr.co/edit/vXeVoFYVU2IU08CF Issue with angul ...

Requests in WebForms that retrieve JSON data using the GET method and allow for the data to

Currently working on an older WebForms project that requires some updates to include new features. I am aiming to retrieve data using $.getJSON(). This process is straightforward in ASP.NET MVC with the ability to return data like this: return Json(data, ...