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

Is there a way to implement DnD functionality on a dynamically generated div element within an HTML page using Dojo

Is it possible to implement drag and drop functionality on dynamically generated div elements using Dojo? I have experimented with various methods to incorporate this feature. Below is a snippet of my code: var inputdiv = document.createElement('div& ...

Creating unit tests for a state that includes PreparedQueryOptions within Jasmine framework

Currently, I am in the process of writing a Jasmine test case for the state within Angular JS. The resolve section of my state looks something along these lines: resolve: { myResult: function () { var dfd = $q.defer(); ...

Is it possible to conceal any spans that are in close proximity to the cursor when hovered over?

Currently, I am working on a project that involves multiple spans placed side by side, with each span containing a letter of the text. My aim is to create a functionality where hovering over one of these spans will not only hide that particular span but al ...

Determine whether a div that has been generated automatically has been selected by the user

My JSON file contains a list of elements, each creating a container. See the code below: $.getJSON('/data/risks.json', function(data) { var html = ''; $.each(data.risk, function(key, value){ html += '<div class="elementlis ...

Having trouble getting $.ajax to function properly in conjunction with fullcalendar js?

Currently in the process of utilizing the Smart Admin Theme, specifically focusing on the functionality within the calendar page. The calendar's core features are operational, allowing for the creation and placement of new events on the map. My curr ...

Rails controller did not receive the Ajax call

I have noticed that when I make an Ajax call using jQuery, the data is always transmitted (status 200), but there are times when it's not properly received by the Rails controller. The data is sent correctly, but most of the time the controller respon ...

Transferring data from JavaScript to PHP with the help of AJAX

I am encountering issues with my code, as I cannot seem to successfully send coordinates from JavaScript to PHP using AJAX. Although I can retrieve values from JavaScript into a textbox, the values are not being transferred to PHP. Any assistance on resolv ...

Tips on maintaining the parent's scope in CoffeeScript while making an AJAX call

I need to iterate through an object in CoffeeScript and make an AJAX call for each item in the object using jQuery. However, I'm facing an issue with losing the reference to the initial context in the callback function of the AJAX call. The context al ...

Incorrect Matching with Regular Expressions

I'm working on a regular expression to validate a URL. var url = "https://www,google.com"; var urlRegex = /(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&@#\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&@# ...

What is the location where Three.js establishes the default shaders for materials?

I've been attempting to locate the exact location where the fragment and vertex shaders are being assigned after creating a Three.js material, but haven't had much success. Using the ParticleSystemMaterial, I have material = new THREE.ParticleSy ...

Encountered an issue while installing the "sharp" module on MAC M1

When I run npm run dev (gatsby develop) on my MacBook Pro M1 chip, it exits with the error message: Error: Something went wrong installing the "sharp" module However, when I run npm run dev on a MacBook Pro with an Intel chip, everything works fine. I&ap ...

Mastering the art of knowing when to implement asynchronous and synchronous programming techniques is essential for

As I explore asynchronous programming in JavaScript, I am faced with the challenge of integrating two email providers: Sendgrid and Mailgun. My goal is to send an email using one provider, and if any errors occur during the process, automatically resend th ...

Click the button to add content to the top section of the div using jQuery

Looking for some assistance with a web development issue I'm facing. Here's the scenario: I have two sections on my webpage - TOP and BOTTOM. In the bottom section, there are 3 list records each with a checkbox and button. What I need help with ...

Can you explain the distinction between angular-highcharts and highcharts-angular?

Our team has been utilizing both angular-highcharts and highcharts-angular in various projects. It appears that one functions as a directive while the other serves as a wrapper. I'm seeking clarification on the distinctions between the two and recomme ...

What is the process for including a new item in an array of objects?

const data = [ { title: 'Tasks', items: ['complete assignments', 'study for exams'], }, { title: 'Ongoing', items: ['learn new skills', 'work on projects'], }, { titl ...

What is the best way to set a newly selected HTML option as the first choice?

I'm facing a simple problem in JavaScript that I can't seem to crack. Admittedly, I am new to working with JavaScript. My issue lies with sorting a dropdown list in alphabetical order while also keeping the selected value at the top. Whenever a ...

Sending information from the parent component to the child Bootstrap Modal in Angular 6

As a newcomer to Angular 6, I am facing challenges with passing data between components. I am trying to launch a child component bootstrap modal from the parent modal and need to pass a string parameter to the child modal component. Additionally, I want t ...

Exploring the functionality of multiple index pages in angularjs

I am trying to access the localhost:3000/admin which is located in my views. The index.html and admin.html are two separate base files, one for users and the other for the admin dashboard respectively. Here is a snippet from my app.routes.js file: angul ...

For an unknown reason, I am facing difficulties in using the Storage feature from @angular/fire in ANGULAR 16

Recently I started exploring Angular/Fire and decided to test out some of its features by creating a basic app. Firestore and authentication were working smoothly, but when I attempted to include Storage, an error message popped up: ERROR FirebaseError: ...

What is the best way to incorporate variables into a text file using ajax?

I am having an issue with my code. I have written a script that allows users to draw an image on canvas and then extract pixel values from the clicked location, writing them into a text file using ajax. However, I am facing problems with my onclick and a ...