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

Spotfire: Changing a URL in an input field after it has been entered by the user

Currently, I am faced with a challenge related to importing a file in spotfire based on the path provided by the user. To accomplish this, I am utilizing a data function written in R script. In R, it is essential to note that all "\" characters are n ...

Angular JS is throwing an error because angular.model is not recognized as a function

I am experimenting with some angular JS examples, but I have encountered an error that is causing me some trouble. Can someone please assist me in resolving this issue? <html> <head> <script src="http://ajax.googleapis.com/ajax/li ...

Making an AJAX call to a PHP script to add data

Could you assist me in understanding why my code is resulting in a double insert? I have a JavaScript function that makes an AJAX request to a save.php file to insert data into a database. However, each time I submit it, it performs the insertion twice, al ...

Using Angular and Typescript to implement a switch case based on specific values

I am attempting to create a switch statement with two values. switch ({'a': val_a,'b': val_b}){ case ({'x','y'}): "some code here" break; } However, this approach is not functioning as expected. ...

In the event of any unexpected errors while utilizing an API, a ticket will be automatically generated on Jira through the use of Vue.js

After successfully hitting the API through Postman and creating a ticket on Jira, I encountered a CORS error when attempting to do the same using an index.js file in VueJS. The flow is unclear to me as generating a demo error results in nothing being sho ...

AngularJS provides users with the ability to access additional information by matching specific identification

Is there a simple way in Angular to display the label of an item from an array without looping through it? I have an array of color options: $scope.colors=[ {id:"0",label:"blue"}, {id:"1",label:"red"}, {id:"2",label:"green"} ] And my data object store ...

Error: Unable to run 'play' on 'HTMLMediaElement': Invocation not allowed

Just a simple inquiry. I am trying to store an HTMLMediaElement method in a variable. // html segment <video id="player" ... /> // javascript segment const video = document.querySelector('#player') const play = video.play video.play() / ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...

The application of the template string expression is not carried out by $compile in the link function of a directive

I'm still learning AngularJs and running into a few issues with the code below. return { require: ['^myElement'], restrict: 'EA', replace: true, scope: true, link: function (scope, element, ...

Setting the Date in Angular.js: A Step-by-Step Guide

Make maxDate selectable as today at the latest (past days are clickable but not tomorrow). The range between minDay and maxDay should not exceed 365 days, allowing for fewer days to be selected. $scope.dateOptions = { formatYear: " ...

Verify whether the labels are blank, remain as they are, or transfer the data to the database

Currently, I am utilizing PHP, HTML5, and JavaScript for my project. The task at hand involves creating a webpage that will be connected to a database. However, I have encountered an issue wherein the page proceeds to the next step and sends data even when ...

acquire data from a JSON array

Attempting to extract the SKU from a URL www.mbsmfg.co/shop/coles-grey/?format=json-pretty in JSON format, and display available values under variants for that specific product to users. For example, when a user visits www.mbsmfg.co/shop/coles-grey/, th ...

Strip the CSS styling from an image (the CSS being included in the generated code)

I need to remove the CSS styling from an image, but I can't modify the generated code where it's coming from. My actual code looks like this: <div class="bubble"> <img id="one" src="/static/webupload/MyronArtifacts/images/descarga.png ...

Continue running the ajax request repeatedly until it successfully retrieves results

At the moment, I am using a basic ajax call to retrieve data from our query service api. Unfortunately, this api is not very reliable and sometimes returns an empty result set. That's why I want to keep retrying the ajax call until there are results ( ...

Having trouble toggling webcam video in React/NextJS using useRef?

I have created a Webcam component to be used in multiple areas of my codebase, but it only displays on load. I am trying to implement a toggle feature to turn it on and off, however, I am facing difficulties making it work. Below is the TypeScript impleme ...

Switch the designation to Hover Class

I am working with nested divs and have assigned a CSS class to one of the inner divs. How can I trigger the hover effect of the class (class.hover) when the user hovers over the outer div, even if they are not directly over the inner div? I believe this m ...

Executing a function while adjusting a range slider

Having an <input type="range"> element on my website presents a particular challenge. To handle changes in this element, I am using the following function: $("#selector").bind("change", function() { //perform desire ...

What is the method for including word boundaries in a regex constructor?

export enum TOKENS { CLASS = 1, METHOD, FUNCTION, CONSTRUCTOR, INT, BOOLEAN, CHAR, VOID, VAR, STATIC, FIELD, LET, DO, IF, ELSE, WHILE, RETURN, TRUE, FALSE, NULL, THIS } setTokenPatterns() { let tokenString: s ...

Adjust the settings of a CSS element

Apologies as I am still new to this and struggling to implement the correct code. I am attempting to modify the background color of a custom marker in leaflet.js. Essentially, I need to adjust the CSS element's value. I have the CSS code and how I am ...

What is the process for extracting components from a JSON file using an observable in Angular?

Take a look at this snippet of code: response: any; fetchData(url: any) { this.response = this.http.get(url); } ngOnInit(): void { fetchData("url.com/data.json"); console.log(this.response) } When I check the console, I see Obser ...