When adding an object to an array in AngularJS, it seems to trigger updates for

Currently, I am fetching data from a WebAPI and then storing it in an array called products, which is scoped.

$scope.products

In addition to the products array, I also have another scoped array named selectedFish.

$scope.selectedFish = [];

My objective is to locate a specific product within the products array, make modifications to it, and subsequently add it to the selectedProducts array.

Within the same controller, I have implemented the following function:

// Function to add a new fish to the selectedFish array
            $scope.add = function() {
                // Locate existing fish from the products list
                var newFishToAdd = $filter('filter') ($scope.products, { Id: $scope.selectedProduct });
                // Modify the name property
                newFishToAdd[0].FishName = $scope.selectProductName;
                // Add the new fish to the selected fish array
                $scope.selectedFish.push(newFishToAdd[0]);
                $scope.bindModel();
            }

While this approach does work, I am encountering issues when attempting to add the same product multiple times with different FishName values. It seems to update all entries in the array for the same selectedProduct with the last entered FishName value.

Answer №1

When encountering the issue of object reference being the same, it's important to make use of angular.copy().

$scope.add = function() {
    // Locate existing fish in the products list
    var newFishToAdd = $filter('filter')($scope.products, { Id: $scope.selectedProduct });

    var obj = angular.copy(newFishToAdd[0]);
    obj.FishName = $scope.selectProductName;

    // Append new fish to the selected fish array
    $scope.selectedFish.push(obj);
    $scope.bindModel();
}

Answer №2

For this particular task, it is recommended to consider using angular.copy. The official documentation for Angular provides detailed information about this method (https://docs.angularjs.org/api/ng/function/angular.copy)

angular.copy

Essentially, angular.copy creates a thorough duplicate of the specified source, which should either be an object or an array.

If no destination is given, a duplicate of the object or array is generated.

In case a destination is provided, all its elements (for arrays) or properties (for objects) are removed before transferring all elements/properties from the source to it.

If the source is not an objector an array(including null and undefined), then the source itself is returned. An exception will be triggered if the source happens to be the same as the 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 best way to substitute unpredictable dynamic variables on-the-fly?

I am working with a .js file that contains a config structure similar to this: genGetLocations:{ data_url:'restaurants/{var1}/tables/{var2}, } This is just one example. Some configurations may have data_url with more than two dynamic variables. I ...

The error message "Uncaught TypeError: Unable to retrieve the 'length' property of an undefined object in Titanium" has occurred

Here is the data I am working with: {"todo":[{"todo":"Khaleeq Raza"},{"todo":"Ateeq Raza"}]} This is my current code snippet: var dataArray = []; var client = new XMLHttpRequest(); client.open("GET", "http://192.168.10.109/read_todo_list.php", true); c ...

Avoiding the opening of a select menu

Is there a way to prevent the dropdown menu from appearing when a select element is clicked in a form? I have attempted two methods but they did not work: $('select').click (function (e) { console.log (e); return false; }); and $(&apo ...

Checkbox: Activate button upon checkbox being selected

On my webpage, I have a modal window with 2 checkboxes. I want to enable the send button and change the background color (gray if disabled, red if enabled) when both checkboxes are selected. How can I achieve this effectively? HTML: <form action="" me ...

Updating HTML Pages with Dynamic Content

Dealing with a massive project consisting of 50,000 pages (20,000 aspx forms, 10,000 asp forms, and 10,000 html pages) can be overwhelming. With only 2 days to complete the task of adding content after the body tag on all pages, I am seeking advice on ho ...

Styling a <slot> within a child component in Vue.js 3.x: Tips and tricks

I'm currently working on customizing the appearance of a p tag that is placed inside a child component using the slot. Parent Component Code: <template> <BasicButton content="Test 1234" @click="SendMessage('test') ...

Retrieve all populated fields on the second tier using Node.js and Mongoose

Do you have any insights to share on Node.js and mongoose? I've defined a mongoose schema and when I use findOne(), it returns a document with multiple elements under the "resource" key. Below is an example of how the document looks like: { "met ...

Creating Virtual Nodes from a string with HTML tags in Vue 2.5: A Step-by-Step Guide

Having some trouble creating a functional component that displays the Feather Icons package - I'm stuck on the final step. Here's what I have so far: This is my FeatherIcon.vue component. <script> const feather = require("feather-icons"); ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

Combine two elements in an array

I am faced with a challenge in binding values from an Array. My goal is to display two values in a row, then the next two values in the following row, and so on. Unfortunately, I have been unable to achieve this using *ngFor. Any assistance would be greatl ...

The function "classList.add" does not successfully add a class to both a div and form elements

I've encountered an issue where I am unable to add a class to div/form elements using the classList.add method. Interestingly, this method works perfectly fine for other elements like input or button. However, when it comes to the div and form element ...

A table featuring an HTML select element that allows users to choose from preset options or manually enter

My goal is to incorporate a select box where users can either choose from a set list of options or input their own custom value. The select element is nested within a table. Unfortunately, using datalist is not a viable solution for me in this case. I have ...

Guide to showcasing console output on a Web Server

Apologies if this question is not the most suitable for this platform. I recently set up Pure-FTPd service on a CentOS server. To check current connections, I use the command pure-ftpwho, which gives me the following output: +------+---------+-------+---- ...

What is the best approach for managing multiple socket rooms?

I have been working on developing a chat application that supports multiple chat rooms. After watching several tutorials, I have devised a way to handle this. const io = require("socket.io")(http); io.on("connection", (socket) => { ...

Adjust the node's location in Cytoscape.js

I recently switched from using Cola to fCose in Cytoscape.js for graphing multiple graphs with no connections. With Cola, I was able to manually set node positions by tweaking the layout options. However, with fCose, despite adjusting variables like quali ...

Working with Angular: Dealing with ngRepeat and Empty Inputs

I am currently working on a project where I have an ng-repeat with a list of inputs. Interestingly, if the inputs are empty, the corresponding LI is hidden. <li ng-repeat="(key, value) in jewel" ng-if="value !== ''"> <input ng-mode ...

What is the best way to iterate through my array and display each value within my button element?

I have a challenge where I'm trying to iterate over an array named topics. This array contains the names of various people. Within my loop, my goal is to extract each name and insert it into a button as text. When I use console.log within my loop, I ...

Converting an Observable Array into a nested JSON structure

Having difficulty storing an array of information properly as JSON. A visual representation of the issue can be seen in this fiddle. Input a set of tags and check the console for output. Additional detail: An input captures a comma-separated list of tag ...

Unraveling the Mysteries of Node.js Application Logging

We've been having smooth sailing with our Kube cluster on AWS, but there seems to be a recurring issue with our Node app crashing and generating repetitive logs from our instances... I've scoured the internet for solutions but haven't had m ...

Is there a way to use jQuery to hide rows in a data table that contain a specific code, such as "1.1" or "1.2," that includes a

When using ajax, I pass data from two inputs to another page. These values are then used in a query to display the results in a data table on the main page within the success function. Now, I'm looking to implement a condition where any data containi ...