When two $scopes are updated simultaneously, it leads to the duplication of data

Here is the snippet of code I am working with:

  $scope.addToOrder = function(index) {
        var tempItem = $scope.item;

        if (tempItem[index].validate == true){
            if (_.isEmpty($scope.item2) == true) {
                $scope.item2.push(tempItem[index]);
            } else {
                for (var i = 0; i < $scope.item2.length; i++) {
                    if ($scope.item2[i] == tempItem[index]) {
                        break;
                    }

                    if (i == $scope.item2.length - 1) {
                        $scope.item2.push(tempItem[index]);
                    }
                }
            }
        }
    }

I am trying to transfer data from one object to another (from item to item2). While it seems to be working fine, any changes made to item are also reflected in item2, which is not the desired behavior. What am I missing here?

Answer №1

When you currently have an object reference, any modifications made to one will also affect the other.

To avoid this issue, consider utilizing angular.copy

$scope.addToCart = function(index) {
    var tempProduct = $scope.product;

    var productCopy = angular.copy(tempProduct[index]);

    if (tempProduct[index].selected == true){
        if (_.isEmpty($scope.cartItems) == true) {
            $scope.cartItems.push(productCopy);
        } else {
            for (var i = 0; i < $scope.cartItems.length; i++) {
                if ($scope.cartItems[i] == tempProduct[index]) {
                    break;
                }

                if (i == $scope.cartItems.length - 1) {
                    $scope.cartItems.push(productCopy);
                }
            }
        }
    }
}

Answer №2

Utilize angular.copy to duplicate by value

 angular.copy($scope.source, $scope.destination);

or

 $scope.source = angular.copy($scope.destination);

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 process for changing proxy settings through the command line when using Create React App?

I recently created a React project using Create React App and set up the development server to proxy API requests through the proxy setting in my package.json: ... "proxy": "https://dev-backend.example.com" ... However, I am looking ...

Assess transcluded content prior to template compilation in an AngularJS directive

I am currently developing a custom "collapseText" directive using AngularJS. The purpose of this directive is to display a specified maximum number of characters and provide a "Read More" option to expand the text if it exceeds the limit. My goal is for t ...

What could be causing the invalid hooks error to appear in the console?

I'm completely stumped as to why this error is popping up when I try to use mutations with React Query. Any insights or advice would be greatly appreciated. Note: I'm implementing this within a function component in React, so it's puzzling ...

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...

Issue when sending PHP Papa Parse object through AJAX

I am currently working on extracting a CSV local file in PHP using AJAX and have found success with Papa Parse. However, I am facing difficulties passing the results with AJAX. Despite trying various methods such as JSON.stringify, passing only the first f ...

When we typically scroll down the page, the next section should automatically bring us back to the top of the page

When we scroll down the page, the next section should automatically bring us back to the top of the page without having to use the mouse wheel. .bg1 { background-color: #C5876F; height: 1000px; } .bg2 { background-color: #7882BB; height: 1000px; } .bg3 ...

Customize Google Chrome to display a vibrant splash screen instead of a boring white blank page when

"I've been on the lookout for Chrome apps that can help make my screen darker or inverted to reduce eye strain. While I have found some apps that do the job, there's one thing they don't seem to be able to override - the White Blank page. W ...

Show full-screen images on click using Ionic framework

Currently, I am working on developing a mobile app using the Ionic framework. I have created a layout that resembles the one shown in this Card Layout. My question is: How can I make the card image display in full screen when clicked by the user and retur ...

Showing the information obtained from an API request once the user submits the form without the need to reload the page

I am currently working on a form that will take search query requests from users upon submission and then display the results by making an API call. My goal is to show these results without the page having to refresh, using AJAX. The backend connection to ...

What is the process for creating a list using layers that are published in Geoserver?

I am currently working on developing a webmapping application. One of the tasks I need to accomplish is parsing the WMS request in order to retrieve the title of each layer within the layers section: var xhr = new XMLHttpRequest(); xhr.open(' ...

Dynamic Selection of JSON Key-Value Pairs in React Framework

My json data structure resembles the following: { "index": 1, "ln": "27953", "name": "Product 1", "availability": { "day0726": "G", "day0727": "G", "day0728": "G", } } I am looking for a way to dynamically disp ...

Enhanced Rating System for Asp.Net

How can I retrieve the selected value (CurrentValue) of the ASP.NET Rating control in javascript? I have it implemented within a datagrid, and I am facing difficulty in accessing the CurrentValue property. Any suggestions or solutions for this issue woul ...

Learn how to rearrange the order of Vue elements

I am working with a specific object structure in my code: lines: [{ order: '1', text: ' blue' },{ order: '2', text: 'green' },{ order: '3', text: 'yellow' }] Currently, thi ...

One important rule to remember when using React Hooks is that they must be called consistently and in the correct order in each render of the component. It

Encountering an issue while trying to use the ternary operator to determine which React Hook to utilize. The error message states: "React Hook "useIsolationDynamicPhase" is called conditionally. React Hooks must be invoked in the same order during every co ...

What is the best approach to establish multiple global prefixes in a NestJS project?

I am looking to define multiple Global Prefixes for my application such as: admin/products admin/users admin/... api/products api/search api/... shop/products shop/cart shop/... In the main.ts file, I can set a single global prefix using th ...

Disable the functionality of the next and previous buttons for the Bootstrap carousel when clicking on the outer

Here is the code for the carousel: The next/prev button functions under its respective div, how can I stop it? When I click on the div below the carousel, the carousel continues to move as usual. Below the carousel div, there is another one with a tabbi ...

Adding names in real time to a list within a template

I am currently facing an issue while attempting to dynamically add and populate values in an array. Strangely, I am unable to see any output from a console.log statement. This has left me perplexed as to why there are no errors or logs being displayed. Co ...

What is the process for adding a dot to the package.json file using the npm-pkg command?

I need help using the npm pkg set command to create a package.json file with the following structure: { ... "exports": { ".": { "import": "./dist/my-lib.js", "require": "./dist/my-l ...

Restricting Checkbox Choices with JavaScript by Leveraging the forEach Function

I am developing a checklist application that limits the user to selecting a maximum of three checkboxes. I have implemented a function to prevent users from checking more than three boxes, but it is not working as expected. The function detects when an ite ...

What is the best method for removing node and then reinstalling it using nvm?

In my Mac, I have successfully installed Nodejs, but it was done using the usual method. However, in my new role, I've been asked to utilize NVM for Node installation. Can you guide me on the best approach to uninstall Node and then reinstall it with ...