A JavaScript function that instantiates an object that invokes its own function

Currently, I am working on an Angular service that is meant to return a new object.

Everything seems to be fine and in working order. When I use new MakeRoll(), it successfully creates an instance. However, the issue arises when I call self.add towards the end as it also attempts to create a new instance using new MakeRoll(), but doesn't function as expected.

I have tried multiple approaches to solve this problem, but unfortunately, haven't been able to come up with a solution yet.

var services = angular.module('services', []);

services.factory('Roll', [function() {
  var MakeRoll = function () {
    var self = {};
    self.rolls = [];
    self.add = function(number, sizeOfDice, add) {
      var newRoll = {};
      newRoll.number = number || 1;
      newRoll.sizeOfDice = sizeOfDice || 6;
      newRoll.add = add || 0;
      newRoll.rollDice = function() {
        var result = 0;
        var results=[];
        for (var i = 0; i < newRoll.number; i++) {
          var roll = Math.floor(Math.random() * newRoll.sizeOfDice) + 1; 
          result += roll;
          results.push(roll);
        }
        newRoll.results = results;
        newRoll.result = result;
        newRoll.Roll = new MakeRoll();
      };
      self.rolls.push(newRoll);
      return self;
    };
    self.remove = function(index) {
      self.rolls.splice(index, 1);
    };
    self.get = function(index) {
      return self.rolls[index];
    };
    return self;
  };
  return new MakeRoll();
}
]);

Answer №1

Angular services are specifically designed as singletons to handle important business logic, so make sure not to confuse plain models with Angular services. If you need multiple objects, consider creating a constructor and linking it within the service for seamless operations.

function MakeRoll() {
...
}

angular.module('service', []).factory('Roll', function () {
    var rolls = [];

    return {
        add: add,
        remove: remove,
        get: get
    }

    function add() {
        // var o = new MakrRoll();
        // rolls.push(o);
    }

    function remove(o) {
        // Remove o from rolls
    }

    function get(o) {
        // Get o from rolls
    }
});

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 reason for the JavaScript TypeError (undefined) being triggered when this object is used within a function?

I have defined a new object like this: function node(){ this.tag = null; this.Tdata = []; this.Tchilds = []; } Now, I am trying to use this object in a function: function Validate(root /*Ass ...

Leverage scope Variable in Angular Service URL

Currently, I am aiming to retrieve data from an API by sending specific search parameters through an AngularJS service. Within my ng-model, I have a variable named "search" that I want to utilize as a parameter in the API URL. My initial (unsuccessful) at ...

What is the best way to update a Vue.js input element using JavaScript?

Looking to use a Vue.js input for automated testing purposes. How can I successfully set a value and submit it without it being automatically changed back to default data? I have tried the following method to set the value, but it keeps getting overridden ...

Is there a similar feature to RxJs version 4's ofArrayChanges in RxJs version 5?

Currently utilizing Angular2 and attempting to monitor changes in an array. The issue lies with only having RxJs5 available, which appears to lack this specific functionality. ...

Can Vue-router be used to load screens into Tabs?

In my setup, I have a routes file with multiple routes configured such as localhost:8000/test and localhost:8000/test2. My objective is to create a final route like localhost:8000/tabs, where I can utilize a tab library like bootstrap or Vuetify to displa ...

Navigating through a web application with AngularJS ui-router often involves passing parameters

I'm working on an AngularJS webapp using ui-router, and I have a state that contains multiple views. My goal is to utilize the same template/controller in two different views with a parameter. Both the template and controller are already set up. . ...

What is the syntax for implementing the 'slice' function in React?

While working on my React app, I encountered an issue when trying to extract the first 5 characters from a string using slice. The error message displayed was: TypeError: Cannot read property 'slice' of undefined I am utilizing a functional compo ...

Comprehending the significance of *this* within class structures

I've got this code snippet below. class Node { constructor(value, parent, possibleChildren = []) { this.value = value; this.parent = parent; this.children = [] this.setChildren(possibleChildren); } setChildren(possibleChil ...

When the webpage first loads, the CSS appears to be broken, but it is quickly fixed when

Whenever I build my site for the first time, the CSS breaks initially, but strangely fixes itself when I press command + s on the code. It seems like hot reloading does the trick here. During development, I can temporarily workaround this issue by making ...

Is it feasible to develop an asynchronous function in Node.js that executes concurrently?

My objective is to simultaneously execute the longRunnigTask and quickTask functions: function longRunnigTask() { return new Promise((resolve) => { console.log('longRunnigTask started'); for (let i = 0; i < 999999999; i+ ...

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

What is the best way to select the initial element from my class within my component using protractor?

Can anyone help me figure out how to click on the button in this component? I need guidance on navigating through the following path: Is xpath my only option for doing this? I believe a css locator could work as well, but I am unsure of how to construct ...

Enabling and disabling contenteditable functionality on a div element in Angular

Issue I am facing an issue while trying to bind a boolean to the contenteditable directive of a div. However, it seems that this binding is not working as expected. Error Message: The 'contenteditable' property is not recognized as a valid p ...

Determine the item in a collection of objects that contains a specific key

What is the most efficient method for locating an object by a specific key in JS when given an array of objects? Utilizing jQuery and underscoreJS is acceptable. I am simply seeking the simplest solution with minimal code. Illustration: Suppose we have a ...

Creating an identifier for the jQuery slideToggle function involves assigning a unique class or ID to

I am currently working on creating an identifier for the jQuery slide.Toggle function. In my PHP code, I have a loop that prints values, each with a button and a div that should be able to slide toggle. So far in PHP, here is what I have attempted, withou ...

"Troubleshooting why the jQuery Click Function is malfunctioning specifically in

Can someone help me troubleshoot this animate out script? It works fine on chrome, but not on Firefox and I can't seem to figure out why. Any suggestions? The script is designed to animate certain elements when a specific link is clicked. <scrip ...

Tips for creating a stylish navbar with a faded effect on the right side and integrating a fresh button into its design

I'm looking to enhance my Navbar by implementing a feature where, if the width of the Navbar exceeds that of its parent div, it will fade on the right side and a new button will be added - similar to what can be seen on Youtube. 1- When the Navbar&ap ...

Stay connected with AJAX's latest updates on Twitter with just 13 bytes

Twitter sends a POST request of only 13 bytes when someone follows an account. This small amount of information helps to reduce latency and server load, providing advantages for web developers. However, removing unnecessary cookies and extra information f ...

What is the process of adding CSS effects to a button when a keypress activates it?

Do you have a CSS style that transforms the look of a button when clicked on-page? Want to extend this effect to when the button is activated via keyboard? (In essence, browsers allow activating a button by pressing Tab to give it focus and then hitting S ...

Ajax causing unreliable posts

I am facing an issue with sending and receiving data in my mobile application. I currently use the jquery $.post function, but it seems to be quite unreliable. Issue: Occasionally, about 1 out of 10 times, the POST request is sent successfully, but the ca ...