Does modifying data from an AngularJS service update the original data within the service?

Accidentally, I managed to create something that works but feels like it shouldn't! Essentially, I have a JSON data with a list of items that can be selected by the user, modified, and then saved. Here is a simplified version of the code:

app.service("ItemData", ["$http", function ItemDataService($http) {
this.items = [];
var _this = this;

this.fetch = function() {
    var promise = $http.get("items.json");
    promise.then(
        function(payload) {
            _this.items = payload.data;
            console.log(_this.items); 
        }
    );
    return promise;
};

this.getFirstItem = function() {
    return this.items[0];
}

this.update = function() {
    console.log(this.items)
};
}]);


app.controller("PageCtrl", ["$rootScope", "ItemData", function($rootScope, ItemData) {

    var _this = this;
    $rootScope.item = null;

    var promise = ItemData.fetch();
    promise.then(
        function(payload) {
            setTimeout(function() {
                $rootScope.item = ItemData.getFirstItem();
                $rootScope.item.name = "why does this change the original service?";
                ItemData.update();
            }, 5000);
        }
    );
}]);

When ItemData.update is called, the logs reveal the changes made. However, my expectation was for $rootScope.item to be a copy rather than a reference to the original. Isn't that the usual behavior with function returns? Why does it also affect the original data here?

I am new to AngularJS, so there might be better approaches. Hence, my question has two parts - why does the current code behave this way, and are there alternative methods?

Answer №1

Utilizing fundamental JavaScript principles, the code returns a reference to the object in order for any changes made to be reflected in "the root". To create a fresh copy before returning it, consider using angular.copy().

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

Tips on how to retain data from ajax requests when navigating between pages

Background Information In my web application, there is a search page with 3 dropdown boxes that are filled via ajax. The first box contains default locations upon loading the page. When a location is selected, a second dropdown appears with buildings from ...

Dealing with errors when working with cross-domain JSONP requests in jQuery can be a

My attempts to capture a bad request error using my jquery code have been unsuccessful. $.get('http://example.com/', {}, function () {}, 'jsonp') .done(function () { // never fires }) .fail(function () { // never fires }) .a ...

JSfiddle not loading properly on website

I am facing an issue with my Jsfiddle code. It works correctly there, but when I copy it into my webpage along with the CSS and JavaScript files, it doesn't work. Can anyone provide insight on how to properly transfer the code to display it correctly ...

Navigate post Ajax call

When I make an unauthenticated GET request using AJAX, my server is supposed to redirect my application. However, when I receive the redirect (a 303 with /login.html as the location), the response tab in the Firebug console shows me the full HTML of the lo ...

Is there a way to display the total number of rows in an ng-repeat loop?

I would like to display a table on my website that contains data in the following format: <tr data-ng-repeat="row in grid.data | filter:isQuestionInRange"> <td>{{ row.problemId }}</td> </tr> Is there a method to include a count ...

Is it necessary to use Hapi.js on the client side in order to establish a websocket connection using the Hapi.js protocol?

Currently, I am in the process of developing an API using Hapi and requiring WebSocket functionality. After some research, it appears that Nes is the preferred choice to integrate with Hapi for this purpose. Fortunately, Nes simplifies the process signific ...

Interacting with a WebGL globe: accessing database information and displaying pop-up windows when clicking on specific locations on the globe

I am working on creating a WebGL Globe similar to the one found at this link: Currently, I have been using this example as a reference point: Here are the specific project requirements that I am aiming to achieve: The website needs to be able to manage ...

Designing a toggle button interface with Material UI

Looking to add a toggle button to my page. Here is an image of what I have in mind: https://i.sstatic.net/tiQAP.png Unable to find any material-ui component or API for this specific toggle button design. Considering building a custom toggle button with CS ...

Adjusting the Depiction Camera Distortion in Three.js

In my top-down Three.js game, I'm currently using a Perspective Camera. However, I've noticed that it curves a bit too much because it's mainly for "first-person view". Is there a way to customize how objects bend or curve within the frustum ...

Is there a way to prevent users from copying data or switching tasks when using my program or website?

Is it feasible to develop a website or application for Windows desktop machines that can remain focused until the user completes a specific task? For instance, if my YYY app/website is open and I require the user to input some text, I want to restrict the ...

Testing asynchronous functions with Mocha

Currently, I am in the process of developing a node wrapper to interface with an external api. One particular challenge I am facing is testing the asynchronous functionality of the createJob method. Provided below is the test case code: api_key = "test_0d ...

The functionality of Ajax is limited when it comes to handling multiple div elements at the same

Seemingly silly question ahead, but I've been grappling with it for days to no avail. If anyone can help me solve this, please state your price and provide your PayPal details – the money is yours :). What I'm trying to achieve is to add a "Add ...

There is no matching overload for this call in React Native

I am working on organizing the styles for elements in order to enhance readability. Here is the code I have written: let styles={ search:{ container:{ position:"absolute", top:0, }, } } After defining the s ...

techniques for tracking instance variables in a Ruby controller and transferring them to an HTML view utilizing AJAX

Hello, I am looking to create a page that dynamically monitors or renders the value of a variable within the controller as it iterates through different values. view.html.erb <a id='get_value' class="btn">Run</a> <ul id="value_va ...

I have a desire to use Javascript to control CSS styles

Within the CSS code below, I am seeking to vary the size of a square randomly. This can be achieved using the Math.random() property in Javascript, but I am uncertain how to apply it to define the size in CSS. #square { width: 100px; height: ...

Steps for creating an npm package from the /build folder of Create React App

Hello! I am currently working on an app developed using the create-react-app boilerplate. After compiling and building it with npm run build, I now want to transform the /build folder into an npm package for easy use in other projects as a micro app. Can ...

Error message HMR Webpack was found to be invalid

When using Webpack, I keep encountering the following error message: Invalid HMR message, along with a lengthy JSON string. Unfortunately, I couldn't find any helpful resources to assist me in debugging this issue. Do you have any suggestions? https ...

What is the best way to export several 'sub-components' from a single node.js module?

Here's what I mean by exporting 'sub-modules': var fibers = require('fibers'); // this is functional as the 'main' module var future = require('fibers/future'); // also operational as a 'sub' ...

What is the best way to ensure that the buttons remain in place once they have been clicked to reveal a drop-down menu?

Is there a way to keep 3 buttons inline and prevent them from moving when clicked to open a submenu? Changing their positions results in them stacking on top of each other. Any help or suggestions would be greatly appreciated, thank you! Here is the code ...

Can routes be nested in React components?

I'm curious to know if there's a way to integrate nested routes in React, where the Navbar component serves as the parent for dashboard and properties. <Router> <Routes> <Route path='/' element={<Home />} /> ...