Duplicate entry being created in select due to Angular copy operation

There is a select drop-down on my page with three options: orange, banana, and mango. I have a button that allows me to add a new item to the list. When I have orange selected in the drop-down and click the add button to add a new fruit like peach, I end up seeing peach repeated twice. The existing selection of orange gets replaced with peach as well. I am using Angular.copy as shown below, but I'm wondering why this duplication is happening. The list of fruits is fetched from the server, with a fruits arraylist in my action that is parsed as JSON to be displayed on the page.

<select id="fruitSelect" ng-options="fruit.description for fruit in fruits" ng-model="selectedFruit" ng-change="fruitsClicked()"> </select>

Additionally, I have a button that, when clicked, opens a modal asking the user to provide a name to save the fruit to the list.

<button type="button" ng-click="saveFruit()">Save</button>

The JS controller code:

$scope.saveFruit= function() {
        var length = $scope.fruits.push({
          description: angular.copy($scope.form.newFruit)
         });
      $scope.selectedFruit= angular.copy($scope.fruits[length-1]);
    };

My intention is to select the newly added fruit in the drop-down by setting the ng-model selectedFruit to the angular copy value of the last saved fruit. While this method works fine, it results in a duplicate entry. It replaces the previously selected orange with peach in my scenario.

Answer №1

I have provided a solution in a JSfiddle here that I think will be helpful.

In this scenario, there is no need to utilize angular.copy. This method is typically used for duplicating objects where JavaScript would only duplicate the reference.

Based on the information you shared, it seems that you may inadvertently be invoking the function to add the fruit to your array twice, such as using ng-submit on the form and ng-click on the submit button within the same form.

Update:

Updated the JSfiddle. Simply specify the index of your array in the ng-model when switching the selected option.

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

Limit the amount of data possible to input in the HTML editor using AngularJS

Here is the data obtained from the API: <style type="text/css> <!--td {border: 1px solid #ccc;}br {mso-data-placement:same-cell;}--> </style> <span style="font-size:11pt;font-family:Calibri,Arial;font-style:normal;color:#000000;" ...

Using Angular.js Select with ngOptions to group options under a specific label

Exploring the wonders of Angular.js, I have a query regarding ngOptions: Can optgroups be labeled? Imagine two entities - cars and garages. cars = [ {"id": 1, "name": "Diablo", "color": "red", "garageId": 1}, {"id": 2, "name": "Countach", "color" ...

Encountered an unforeseen character 'u' in the initial position of the JSON while attempting to create a plugin

I seem to be encountering some issues with my code. Whenever I attempt to run the script in the developer kit, an error is thrown: unexpected token u in JSON at position 0... funciones.js $(document).ready(function (){ $("#btn1").click(funct ...

Replace the hyphen with a comma using JavaScript

Looking for a way to modify a string like this: "PALS español K- add-on" by replacing the - with ,. The desired output should be: "PALS español K, add-on" Is there a JavaScript solution to achieve this task? ...

"Exploring the possibilities of Sketchfab through an AJAX JSON

Currently, I am on a quest to gather the URL for the thumbnail of a Sketchfab model. To access this information, you can visit: Upon visiting the above URL, all the necessary details are visible to me. My next step involves making an AJAX call to dynami ...

The RxJs Observer connected to a websocket only triggers for a single subscriber

Currently, I am encapsulating a websocket within an RxJS observable in the following manner: this.wsObserver = Observable.create(observer=>{ this.websocket.onmessage = (evt) => { console.info("ws.onmessage: " + evt); ...

Is there a lifecycle function in React Native that runs when the app is not actively being used or is in the background?

Is there a function in react native that runs continuously even when the app is not being used or in background mode? I am looking for a lifecycle function in react-native that operates even when the user is not actively using the app or when the app is r ...

JavaScript: A guide to solving systems of equations

I'm attempting to perform algebraic operations in JavaScript using certain conditions and known variables. However, I lack proficiency in mathematics as well as JavaScript to comprehend how to articulate it. Here are the conditions: var w1 = h1/1.98 ...

What is the best way to apply index-based filtering in Angular JS?

I am working on a tab system using ng-repeat to display tabs and content, but I'm facing some challenges in making it work seamlessly. Below are the tabs being generated: <ul class="job-title-list"> <li ng-repeat="tab in tabBlocks"> ...

What is the best way to switch an element's attributes using only JavaScript?

As I crafted this inquiry, I noticed that most of the analogous questions were along the lines of this one (where the user seeks to toggle an element's class using pure JS) or that one (where the user wants to toggle other attributes with jQuery). My ...

Encountering an error in Express while attempting to upload an image due to the inability to read the property 'file' of undefined

I am currently learning Express framework. I encountered an error while trying to upload an image using Express. The error message I received is "Cannot read property 'file' of undefined." Below are the code snippets that I am using, and I&apo ...

Showing the result of a backend script on the current page using PHP

I currently have a PHP web application that involves submitting data to a backend pipeline, also written in PHP. This pipeline consists of an external script that my application accesses using the 'exec' PHP function. The pipeline follows a multi ...

Converting data to a JSON string using jQuery's AJAX method

When I use document.write() for JSON data, it works fine outside of the AJAX call, but not inside the .done() function. I even tried removing the dataType: 'json' parameter, but it still didn't work. $.ajax({ url: "http://api.wundergrou ...

The error message states that `article.createdAt.toLocalDateString` is not a valid

const mongoose = require("mongoose"); const blogPostSchema = new mongoose.Schema({ title: String, image: String, description: String, createdAt: { type : Date, default : new Date() } }); const blogPos ...

jQuery carousel displaying a blank slide at the conclusion

I am experiencing an issue with my slideshow where it shows an empty slide after the last element. I suspect that there is something in my script causing this behavior, as it seems to be finding one extra child for the element and adding it as an empty spa ...

Manipulate the color of the parent text using a button nested within

I am working on a script that adds a button to div elements with the class name "colors". When the button is clicked, the text color of the parent element will change to a specified color. However, I'm facing an issue where it only changes the last el ...

Leveraging the power of axios.all for dynamic operations

Is there a way to efficiently reuse the same Vue-component for both editing and creating new users? While working with vue-router, I have implemented a beforeRouteEnter method to fetch data via API. Depending on whether an ID is set in the URL parameter, ...

Combining items in Python lists

Suppose we have a string, let's call it s='135', and a list, let's call it A=['1','2','3','4','5','6','7']. How can we extract the values from the list that are also ...

How to maintain the selected value in a Vue.js dropdown even after the page is refreshed

When a user selects a value from a dropdown, it is pushed to the URL. If the page is refreshed, the dropdown should default to the selected value in the URL. This functionality is being implemented in Laravel. I have attempted the following approach, but w ...

Iterate over the keys within a JSON array that begin with a certain key name

Is there a more efficient way to dynamically loop through keys in a JSON array starting with 'option' and either loop through them all or set a maximum limit? Currently, I am using the following approach: $.each(shopifyProductJSON.variants, fun ...