var numerous occurrences of an angular service

In accordance with the document, Angular services are considered singleton instances.

I am currently developing a time-tracking project where I intend to incorporate multiple tasks.

<ul>
    <li ng-repeat="item in data track by $index" >
        <label>Project Name</label>
        <input type="text" ng-model="item.project"/>
        <label>Start Time</label>
        <input type="text" ng-model="item.start"/>
        <label>End Time</label>
        <input type="text" ng-model="item.finish"/>
    </li>
</ul>

<a ng-click="addEntry();">Add Item</a>

Here is an excerpt from my controller:

controller("DashboardCtrl", ['$scope', 'Entry', function ($scope,Entry) {
        $scope.data = [];

        $scope.addEntry = function() {
            $scope.data.push(Entry);
            //$scope.data.push(new jEntry());
        }

    }])

Below is my service definition:

.service('Entry', [function(){
        this.project = "";  
        this.start = "";  
        this.finish = "";

    }]);

My issue arises when I try to create new tasks using a JavaScript constructor (jEntry).

function jEntry() {
        this.project = "";  
        this.start = "";  
        this.finish = "";
    }

When utilizing a service, all tasks seem to be linked as singletons. My question is: what is the appropriate Angular approach for achieving this functionality?

DEMO

Answer №1

One way to handle your service is by returning an instantiable function.

.service('Entry', [function(){
     return function() {
          this.project = "";  
          this.start = "";  
          this.finish = "";
     }
}]);

To use it, simply do $scope.data.push(new Entry());

http://plnkr.co/edit/XTRtWbv1VS5gMmkn7B7e?p=preview

However, this approach might undermine the purpose of having a service. The same functionality could easily be achieved within the controller.

A more efficient method would involve the service keeping track of the entries instead of directly manipulating the scope.

Tracking entries within the service:

Since the entries are treated as a singleton, you can associate them with the singleton and implement methods to manage them. For instance:

.service('Entry', [function(){
  var self = this;
  self.entries = [];
      
  this.add = function() {
    self.entries.push({
      project: "",
      start: "",
      finish: ""
    })
  }
}]);

Rather than inserting the entries object into the scope directly, attach the entire Entry singleton like so:

$scope.data = Entry;

The ng-click function should be updated to data.add(). Moreover, iterate over data.entries instead of just entries. This enables utilizing the Entry object in multiple controllers while maintaining all its data.

Here's an updated version on Plunker: http://plnkr.co/edit/5hs99xMQ3ZOiAWpesD5V?p=preview

You now have the flexibility to incorporate additional functions to Entry, such as creating RESTful methods for storing additions in the database or implementing functionalities to delete entries.

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 alternative method in JavaScript for locating items instead of using indexOf?

I have a set of paths in an array. Some paths are classified as constants while others are labeled as dynamic. A constant path would be something like "/booking-success", whereas a dynamic path could be something like '/arrival/view/:job_or ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

Unlocking the power of JavaScript/HTML integration in CLR

Is it possible to extract HTML and JavaScript into distinct projects, and then retrieve the code by extracting it from the dll in a different project? Any advice on how to access the code from the dll? This is for distributing modules, specifically in MV ...

Exploring the geographical boundaries of a Google Map region using coordinates and polygons

In my quest to develop an Angular application heavily reliant on Google Maps, I aim to showcase areas on the map based on continent -> country -> state -> suburb. The color of these highlighted areas will be determined by the values supplied. I h ...

How can I display an array with keys from php in AngularJS using ng-repeat?

I have a rootScope variable that will store product categories, each category may or may not have child categories. Here is how I assign the rootScope: $rootScope.categoryList = $http.get('category').then((result) -> result.data) This code s ...

Obtain the position of the click

My goal is to generate a 2dgrid with dimensions xMax = 10, yMax = 6 that looks like the following: x 0 1 2 3 4 5 6 7 8 9 _ _ _ _ _ _ _ _ _ _ y |_|_|_|_|_|_|_|_|_|_| 0 |_|_|_|_|_|_|_|_|_|_| 1 |_|_|_|_|_|_|_|_|_|_| 2 |_|_|_|_|_|_|_|_|_|_| 3 |_|_|_|_|_|_|_ ...

developing a custom modal using a button in a React project with Material UI

Hello everyone, I have a question regarding React. I am fairly new to React and need some assistance with adding a new function that creates a Modal. I want to call this function onClick when the add icon is pressed (line 43). Any help would be appreciated ...

Expand Elements to occupy entire width

My CSS skills are still in the early stages. I haven't delved too deeply into it. I have a query regarding how to achieve full width for an element. I've included my code below, but the basic approach I tried using 'width: 100%' didn&a ...

Deciphering the significance behind the initial five lines of code in jQuery

Curiosity piqued, I delved into the jQuery code only to be met with this puzzling snippet: ! function(a, b) { "object" == typeof module && "object" == typeof module.exports ? module.exports = a.document ? b(a, !0) : function(a) { i ...

Replacing strings with special characters appears to be malfunctioning

After spending countless hours searching through Stack Overflow and other resources, I am still unable to understand what is happening here. Any assistance would be greatly appreciated! I am trying to convert document.write('</div>'); to - ...

Having Trouble Importing My NPM Package Using ES6 Import/Export Syntax

I have been working on creating a new NPM package named notifman. Here are the steps I took: Started by creating the package.json: { "name": "notifman", "version": "1.0.5", "description": "Adva ...

Display 'Div 1' and hide 'Div 2' when clicked, then reveal 'Div 2' and hide 'Div 1' when a different button is clicked

I need help figuring out how to make two separate buttons work. One button should display 'Div 1' and hide 'Div 2', while the other button should show 'Div 2' and hide 'Div 1' when clicked. My knowledge of jquery an ...

Is there a way to prevent $http from automatically converting my data into a string enclosed in quotes before sending it?

I'm having some difficulty with formatting the data correctly for an Angular $http POST call to an OAuth token service. Currently, I am parameterizing a simple object like this: $.param({ grant_type: "password", username: 'myuse ...

What strategies can I use to incorporate dynamic filtering using only AJAX while maintaining a functional browsing history?

As I work on implementing AJAX filtering for my e-commerce website, I am exploring different solutions. One approach I am considering involves generating all content statically server-side and then using AJAX requests on the same page with parameters. The ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

Retrieve the ID of the button that was chosen

Hello, I have a card with 3 selectable buttons as described below. <ul class="nav nav-tabs border-0" role="tablist" id="FlightType" onclick="SelectedFlightType()"> <li cla ...

I am experiencing issues with my $ajax request

After running the code snippet below: websiteUrl= "http://192.168.2.171/LoginAuthentication"; $.ajax({ url: 'websiteUrl', type: 'GET', success: function(response) { var title = $(response.responseText).find('a. ...

Executing a javascript function using ajax

My current setup involves using a multiselect dropdown to filter images stored in a database. The issue arises when the filtered results are paginated, as the pagination seems to fail. The filter triggers an Ajax call to a PHP script in order to retrieve t ...

Utilizing Shared Models Across Nested ng-Change Controllers

Within my AngularJS application, I am faced with the challenge of utilizing a value from an input/dropdown field in the second controller when a change event occurs. The structure of my code is as follows: Code snippet (HTML) :: <body ng-app="myApp" ...

Executing Javascript in the background on Phonegap/Cordova for iOS: How to do it?

I've experimented with various plugins in an attempt to run an app in the background on IOS using Phonegap build. Unfortunately, it appears that the app is suspended as soon as it goes into the background. Has anyone found success with any plugins th ...