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

A guide on updating data with Vue-SweetAlert2 by passing user input

I'm currently working on creating a "create" button that will prompt a popup with a text input field for the user, similar to the image below. The expected behavior is that when the OK button is clicked, the name entered in the text field should be s ...

Tips for incorporating a set offset while utilizing the scrollTop() function

I have successfully implemented a code that sets a position:fixed to a div when it scrolls past the top of the screen. The code I used is as follows: var $window = $(window), $stickyEl = $('#the-sticky-div'), elTop = $stickyEl.o ...

Leveraging Three.js Raycaster for a seamless PDF download functionality

Is there a way to trigger a PDF download when clicking on a 3D object in a Three.js scene? Below is an example of how I have set up the Raycaster: var raycaster; var mouse = { x: 0, y: 0 }; init(); function init() { raycaster = new THREE.Raycaster() ...

Run custom JavaScript code dynamically within a webpage

What is the most effective way to use Java to automatically open a web page, run some JavaScript to complete and submit a form, and analyze the outcome? ...

Refine results by searching through the text contained in the elements of every div

I recently came across a helpful fiddle that allows text to be hidden based on what is entered into a search box. However, I am struggling to apply this method to a div that contains multiple elements. Is there a way to modify the jQuery in the provided fi ...

The excessive use of Selenium Webdriver for loops results in multiple browser windows being opened simultaneously, without allowing sufficient time for the

Is there a way to modify this code so that it doesn't open 150 browsers to google.com simultaneously? How can I make the loop wait until one browser finishes before opening another instance of google? const { Builder, By, Key, until } = require(& ...

The request to localhost resulted in a 404 error, indicating that the resource was not found

When attempting a file upload operation using MV.Net, I encountered the GET http://localhost:55298/Home/test2.json 404 (Not Found) error while trying to upload a file. How can this issue be resolved? <input type="file" name="file" ...

Parent's hover element

I am currently working with the following loop: <?php if( have_rows('modules') ): $counter = 0; while ( have_rows('modules') ) : the_row(); ?> <div class="col span_4_of_12 <?php if($counter == 0) { ?>firs ...

"Maximizing battery life: Efficient video playback on iOS in low power

Summary: I am currently working on a website that features a video set as the background which autoplays. However, I have encountered an issue on iOS devices when "Low Power Mode" is activated - the video fails to play and instead displays a large "Play" i ...

Retrieve the current font style with Kendo UI Editor

Recently, I've been facing some challenges while working with the Kendo UI Editor. Specifically, I'm struggling to retrieve the current font style. My goal is to use JavaScript or jQuery to obtain the following values: Values I am looking for: ...

Is it possible to run a JavaScript script from any location?

Currently, I am diving into a Javascript script and in order to run it seamlessly from any webpage I am browsing, I am thinking of adding a button to my bookmarks or using an extension. To be honest, I am clueless about the process and despite doing some ...

Tips for triggering an event from a function instead of the window

Everything is functioning as expected, with the event listener successfully capturing the custom event when it is dispatched from the window and listened for as loading, all seems to be working well. const MyLib = mylib(); function mylib() { const re ...

Utilize the directive method within the transcluded content by making a call

Trying to call a method within a directive from transcluded content. The structure of my HTML is: <typeahead class="typeahead" model="customers" filtered-model="customersfiltered" ng-model="selectedcustomer"> <ul> <li ng-click="select ...

What is the reason for sending a single file to the server?

A function called "import File" was developed to send multiple files to the server, but only one file is being received. Input: <input type="files" id="files" name="files" multiple onChange={ (e) => this.importFile(e.target.files) } ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

Integrating external JavaScript libraries into Ionic using the correct process

For the last few months, I have been utilizing jQuery Mobile for a hybrid app. Now, I am interested in exploring Ionic and Angular.js, so I am attempting to reconstruct it. My current JQM application relies on xml2json.js, but I do not have any experience ...

Tips on adding a tooltip to the react-bootstrap tab element

How can I add a tooltip to the tabs in my React application using Bootstrap tabs? I have three tabs and I want a tooltip to appear when hovering over each tab. import { Tabs,Tab} from "react-bootstrap"; // inside return <Tabs variant="pills" ...

Here's a unique version: "A guide on using jQuery to dynamically adjust the background color of table

I need some assistance with changing the background color of td elements based on the th class. Specifically, I want to target all td elements under the bots class in the HTML code provided below. <table border="1" class="CSSTableGenerator" id="myTab ...

AngularJS does not recognize Model as a date object in the input

I am attempting to utilize AngularJS to showcase a date using an input tag with the type attribute set to date: <input ng-model="campaign.date_start" type="date"> Unfortunately, this approach is resulting in the following error message: Error: err ...