Modifying the data received from a service also updates the data within the service itself

After storing data received from a service in my controller and making edits, I noticed that the changes also reflect back in the original data stored in the service.

JSFiddle Demo

 /* Omitted backend connection section and markdown editor JS code for brevity */    

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

// The PostService in my app caches blog post data from the server on the client side and retrieves single posts
myApp.factory('PostService', function ($log, $filter, $http) {
    var data;

    // Sample data pulled from server
    data = [{
        id: 99999,
        text: "Hello"
    }];

    // Function to retrieve a specific post from the cached data array
    var getData = function (id) {
        if (id !== undefined) {
            var arr = $filter('filter')(data, {
                id: id
            });
            if (arr.length === 0) {
                $log.error('PostService:: getData(' + id + '):: Post Not Found');
                return 'not_found';
            } else {
                $log.debug('PostService:: getData(' + id + '):: Post returned');
                return arr[0];
            }
        } else {
            return data;
        }
    };
    return {
        getData: getData            
    };
});

function ctrl($log, $scope, PostService) {
    var edit = this;

    // Set example post id for editing
    edit.editingId = 99999;

    // Copy the blog post data to be edited
    edit.data = PostService.getData(edit.editingId);

}

This setup is intended for a markdown editor. The goal was to fetch the data from the service into the controller, allow editing, and then update the service with the modified version upon clicking a "Save" button. If this behavior aligns with Angular's databinding principle, what would be a more effective approach to achieve the desired outcome?

Update

In response to feedback from PSL's comment and Thibaud Sowa's answer, I have modified the getData() function to return a copy using angular.copy(). However, it appears challenging to copy a single object from an array (e.g., angular.copy(arr[0])), as it still returns the entire array. Refer to the updated JSFiddle.

Update 2

Upon further investigation, I realized my error and made the necessary corrections, as depicted in the updated fiddle. Thank you for your valuable insights.

Answer №1

When you return an object in JavaScript, it is akin to passing a pointer.

To properly copy an object field by field, use angular.copy like so:

return angular.copy(data);

For more information, refer to the documentation here.

In response to your latest update

I have made edits to your fiddle to demonstrate that you can indeed copy an item from an array. It appears that everything is working as desired (or perhaps I have misunderstood your requirements).

Check out the updated fiddle here.

Answer №2

If you're looking for an easy fix to your issue, consider making a duplicate of the data retrieved from the service.

There are numerous discussions on various platforms about the most efficient methods for deep copying a JavaScript object. One straightforward and quick approach involves using JSON parse and stringify like so:

var duplicatedData = JSON.parse(JSON.stringify(data));

Implement this solution with the information obtained from your service, and you'll be all set :)

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

How to apply background-color to a div element with ng-repeat directive?

Hey there, I'm dealing with the following code: angular.module("myApp", []).controller("myController", function($scope) { $scope.boxList = [{ color: 'red' }, { color: '#F8F8F8' }, { color: 'rgb(50, 77, 32) ...

A guide to retrieving data in React with useSWR whenever the state changes

In a specific scenario, I need to be able to choose users from a dropdown menu. Once a user is selected, the app should display that user's data. Upon loading the page, the app fetches the data for the first user in the array allUsers?.[0]: const [us ...

Replacing scrollbars of a div using overflow:auto with arrow indicators: A step-by-step guide

Currently, I am in the process of creating a small div element that will enable users to scroll between images within a jquery image zoom plugin designed for an eCommerce website. Below is the code snippet that I have developed thus far: <div style="w ...

Tips for safely storing JWT in the browser

I am currently working with Angular 10 on the front-end and obtaining a JWT from backend services. I am seeking the best method to securely store my Okta JWT in the browser while also mitigating the risk of XSS and XSRF attacks. I have looked into storing ...

Tips for arranging elements in proper order following a rotation

Having trouble aligning rotated divs? Let's say we rotate .straight by 30deg, and now we want to find the new offset coordinates of its bottom right corner. This way, we can perfectly match up the bottom left corners of .curve with this new coordinate ...

Easily transfer files without the need to refresh the page by utilizing the power of AJAX

In my page file-upload.jsp, I have the following code snippet: <form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data"> <input type="file" id="upload_file" name="upload_file" multiple="" /> <in ...

The welcome message in Discord.js is displaying the user as a string of numbers instead of their real username

bot.on('guildMemberAdd', user =>{ const greetingMessage = new Discord.MessageEmbed() .setTitle(`Welcome to the server, ${user.user}! We're glad you've joined.`) const channel = user.guild.channels.cache.find(channel =&g ...

How to Generate Web Page Output from HTML 5 Canvas without Printer Prompt

Is there a way to achieve silent printing of HTML5 Canvas content? Currently, I am able to print, but a window always pops up prompting me to select a printer and settings. How can I make the browser print to the default printer without any prompts? I am ...

Instructions for creating a po file from a js file using poedit

Utilizing the Gettext.js library for localizing content created from a JS file has been my approach. The current challenge lies in the manual creation and writing of each po file. It is known that php files can be scanned for gettext strings using PoEdit ...

Unable to Embed Tweets resulting in 403 Error (Forbidden)

While working on embedding some Tweets on my webpage, I encountered the following error message: GET https://cdn.api.twitter.com/1/friendships/exists.json?user_a=19463349&screen_name_b=mrland_news&callback=twttr.setFriendshipExists 403 (Forbidden) ...

When attempting to browse for image files, Postman fails to display images

While trying to upload image files through Postman, I encountered an issue where the browser did not display any image files. It's important to note that I am using Ubuntu as my operating system. https://i.sstatic.net/1D3ro.png When I clicked on "se ...

Error encountered: AxiosError - Request unsuccessful with status code 401 in next.js

My current project uses Next.js, and I've implemented an Axios interceptor to catch rejected promises. However, when there is a server-specific error that requires my attention, Next.js displays the error like this: https://i.sstatic.net/HHhD2.png B ...

Challenges with implementing Node Polyfills in webpack configuration file

I recently started delving into web development and currently tackling a React project that involves connecting to an AWS database. After installing MySql using npm install mysql, I encountered an error message: Module not found: Error: Can't resolve ...

A guide on switching between millimeters and inches in AngularJS dropdown selectors

Blockquote I am in need of a dropdown menu where users can select either MM or Inches. Once a selection is made, all calculations in the form below should be done in that unit of measurement. For example, if MM is chosen, all values should be displayed a ...

Obtain every Scope within an AngularJS application

Is there a method to access all the Scopes within an AngularJS application? This would allow me to manage them at the same level and arrange them in a directive manner or order. Alternatively, is it possible to retrieve all the Scopes of the instances of ...

The JSON output is not displaying correctly

I've been attempting to utilize JSON.stringify in order to format my json object for better readability. However, it doesn't seem to be working as expected. Can someone please offer assistance in identifying what I might have done incorrectly? ...

Implementing drag-and-drop functionality for text on an image using javascript

Hey there, I'm looking to develop a super simple meme creator tool. I have some code for adding text to an image and dragging it around. Can anyone help me out? <html> <body> <div id="draggable-element">Drag me!</div> <styl ...

What is the process of assigning data, in JSON format, from an HTML form to a variable?

I have the coding below in my abc.html file, which converts form data to JSON format: <body> <form enctype='application/json' method="POST" name="myForm"> <p><label>Company:</label> <input name=& ...

Transformation of intricate object

I am currently in search of a reliable utility (such as Lodash) that can assist me in transforming deeply nested objects like the example shown below: Source Data: [{ "category": "blogs", "results": { "__type": "SearchProvider.SearchResultCon ...

Utilizing Jquery's each() method to retrieve the exact position of a specific class element

Is there a way to determine the position of the "owl-item active" element? The current position is 2 out of 3 total photos. <div style="transform: translate3d(-825px, 0px, 0px); transition: all 0.25s ease 0s; width: 48675px;" class="owl-stage"> ...