Prevent the creation of references to objects passed as function parameters in a separate list

I'm facing an issue with modifying items from an array and adding them to a new list of objects.

The problem arises when I make changes to the item in the new list, it also reflects those changes in the original array. It seems like there is some reference linking the new and original items together.

To replicate this problem, please refer to the Controller's comments and run the code as "Full page":

angular.module('app', [])
  .controller('MainCtrl', function($scope){
    
    $scope.items = [
      {id: 1, name: 'item 1'},
      {id: 2, name: 'item 2'},
      {id: 3, name: 'item 3'}
    ];
    
    $scope.newItems = {
      "hello": "World!"
    };
    
    //Function to add selected item object to $scope.newItems
    $scope.addItem = function(item){
      $scope.newItems.item = item;
    };
    
    //Add color property to the previously added object
    $scope.addColor = function(clr){
      $scope.newItems.item.color = clr;
    };
    
    //Although no changes are made to $scope.items, modifications to objects in the new list reflect on the original object.
    
    //For testing purposes
    $scope.$watch('items', function(newValue, oldValue){
        if (newValue !== oldValue) {
          $scope.showProblem = true; //this should NEVER occur
        }
    }, true);
    
  });
<link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="12707d7d66616660736252213c213c27">[email protected]</a>" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="24454a43514845564e5764150a100a1d">[email protected]</a>" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.min.js"></script>

<body ng-app="app">
  <div ng-controller="MainCtrl">
    <div class="alert alert-danger" ng-if="showProblem">
      <strong>UNDESIRED BEHAVIOR:</strong> Original items array has been modified.
    </div>
    
    <ul class="list-group">
      <li ng-repeat="item in items track by item.id" class="list-group-item">
        {{item.name}}
        <a ng-click="addItem(item)" class="badge btn btn-sm btn-success" ng-if="!newItems.item">Add item</a>
        <a ng-click="addColor('red')" class="badge btn btn-sm btn-success" ng-if="newItems.item.id === item.id">Add color property</a>
      </li>
    </ul>
    
    <div class="panel panel-default">
      <div class="panel-body">
        <h3>Original item array</h3>
        <pre>{{items | json}}</pre>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-body">
        <h3>New item list</h3>
        <pre>{{newItems | json}}</pre>
      </div>
    </div>
  </div>
</body>

Answer №1

Great explanation - you nailed it! When it comes to object assignments, they are just references. Let's delve into an example:

let car = { make: "Toyota" }
let newCar = car;

newCar.make = "Honda";
console.log(car.make); // Honda;

Both car and newCar are pointing to the same object - changing one will affect the other. In Angular, there is a handy method called angular.copy(obj) which clones the object without sharing the reference:

$scope.newVehicle.car = angular.copy(vehicle);

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

Why does the map function in JavaScript not allow for a function argument?

I encountered an issue while calling a function and passing an array of objects as the first argument, with the second argument being an object property of the first argument. Strangely, the map function was not accepting the second argument property. He ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

Utilize a single controller for managing two distinct modules within an AngularJS application

Within the first module, I am showing the content details that have been searched for. The goal is to display the description of a specific record when clicking on an image using ng-click. Below is the code snippet I have implemented. Any suggestions or so ...

In need of a method to create PDFs using client-side technology (specifically AngularJS)?

I need a method to create PDFs using AngularJs that includes HTML, CSS, and JavaScript elements. I have tried two options: jsPDF (which does not support CSS) Shrimp (built on Ruby) Neither of these solutions fit my needs. Is there another way to accom ...

Enhancing the style of child elements in jQuery using CSS

My goal is to create a popup that appears upon mouse hover using jQuery and CSS. The code functions properly, but I'm encountering difficulty adding CSS to the child elements within the popup window. Below is the jQuery code: $(document).ready(fun ...

Utilizing JavaScript to dynamically alter an image based on selected dropdown option

I am currently facing an issue with my code where the selected image is not changing when I choose an option from the dropdown list. There are a total of 5 images, but for some reason, they are not displaying correctly. Here is the snippet of my code; < ...

Empty canvas when Material UI Modal transitions states

I've been struggling to make a simple modal using material UI, but every time I try to change the state, it just shows a blank white page. Can anyone help me figure out why this is happening? Here's the code snippet: import {Button,Modal} fro ...

Simultaneous AJAX, animated page loader

My website takes 3 seconds to load due to multiple Synchronous AJAX requests. To enhance user experience, I would like to implement a loading page with an animated GIF. Once the Ajax requests are completed and the page is fully loaded, the loading page sh ...

Is there a way to capture the click event of a dynamically generated row within a panel?

Could you please advise on how to capture the click event of a row that is generated within a panel? I have successfully captured events for rows generated on a page using the , but now I need assistance with capturing events from rows within a panel. I c ...

Encountering difficulty selecting a dropdown sub-menu using Selenium WebDriver

I'm currently working on automating a website with selenium webdriver. The issue I'm encountering is that when I try to click on a menu item, the submenu pops up (actually a misplaced dropdown, UI issue), and although I can locate the element of ...

What are some methods to troubleshoot $injector type errors in TypeScript?

I'm currently facing an issue with my AngularJS code. Here is a snippet of what I have: this.$injector.get('$state').current.name !== 'login' But, it's giving me the following error message: error TS2339: Property 'c ...

Choose the right Vue.js component for optimal performance

I have a primary element within which there is a secondary element with vue.js 2.0. The issue arises when the secondary element relies on methods from the primary element. Here's an illustration: Vue.component('primary-element', { tem ...

Retrieve the information from a website and display it on the current webpage using an ajax request

Is there a way to insert parsed HTML content into my webpage using just a link from another page? I'm attempting to use an AJAX call, but I keep receiving an error. Below is the code I've written, and the browser doesn't seem to be the issue ...

The jQuery .animate function seems to be malfunctioning

I recently came across this jsfiddle link: http://jsfiddle.net/2mRMr/3/ However, the code provided is not functioning as expected: setInterval(function () { box.animate({ left: function (i, v) { return newv(v, 37, 39); }, ...

Gatsby is throwing an error because the location props are not defined

I am attempting to utilize location props in my Gatsby page. In pages/index.js, I am passing props within my Link: <Link state={{eventID: event.id}} to={`/date/${event.name}`}> </Link> In pages/date/[dateId]/index.js: const DateWithId = ( ...

Is it possible to alter the name of a slot before displaying the element in the shadowDOM, depending on the slot utilized in the DOM?

In my project, I am working on implementing different features for both desktop and mobile devices. Some of these features can be replaced by slots. My goal is to have a slot that can be either replaced by a desktop slot called poster-foreground, or a mobi ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Using AngularJS and the ng-show directive, you can set a <div> element to

Objective: My aim is to show the content of a div according to the status of checkboxes, while also ensuring that these divs are visible by default If I have this code snippet: <html> <head> <script src="https://ajax.googleapis.com/ajax/li ...

"Generate a data URL from a Cordova canvas using canvas.to

I have been developing an application that merges 2 images on a canvas and allows users to share it. The app functions well in a browser when run from a local web server, but encounters issues in cordova. All external images are fetched from dataURIs of SV ...

Tips for patiently waiting for a series of asynchronous calls to successfully complete

I have a scenario where I am dealing with multiple asynchronous calls that are dependent on each other's success. For example: function1 = () => { /*Some required Logic*/ return fetch("myurl") .then((json) => { functi ...