Angular does not allow for the insertion of duplicate items into an array

 $scope.updateCart = function(item) {
                var index;
                var items = 0;
                var cost = 0;
                if (item.ref) {
                    $scope.selectedMenueItems.push(item);
                    console.log('updatedd item ' + JSON.stringify($scope.selectedMenueItems));
                } 
}

 $scope.addItem = function(item) {
                console.log('item clicked is ' + JSON.stringify(item));
                var temp = item;
                temp.quantity = 0;
                if (item.item_details.item_sub_category.length > 0) {
                    var itemDetails = item;
                    var modalInstance = $modal.open({
                        backdrop: 'static',
                        keyboard: false,
                        templateUrl: 'template/itemOptions.html',
                        controller: 'itemOptionsController',
                        resolve: {
                            itemDetails: function() {
                                return itemDetails;
                            }
                        }

                    });

                    modalInstance.result.then(
                        function(result) {
                            if (result.length > 0) {
                                temp.totalPrice = temp.originalCost;
                                temp.ref = [];
                                angular.forEach(result, function(info) {
                                    if (!info.option_cumpulsory) {
                                        temp.totalPrice += info.option_price;
                                    }
                                    var item = {};
                                    item.id = info._id;
                                    item.name = info.option_name;
                                    item.quantity = info.quantity;
                                    item.option_cumpulsory = info.option_cumpulsory;
                                    item.price = info.option_price;
                                    temp.ref.push(item);
                                });
                                temp.quantity += 1;
                                console.log('item to be added ' + JSON.stringify(temp));
                                $scope.updateCart(temp);
                            } else {
                                temp.quantity = temp.quantity + 1;
                                $scope.updateCart(temp);
                            }
                        },
                        function(result) {
                            if (!result) {
                                temp.quantity = temp.quantity + 1;
                                $scope.updateCart(temp);
                            }
                        }
                    );
                }
}

When adding a new item with different ref options after already pushing an item, the issue arises where the same ref items are copied for both items. How can I make sure duplicate items have different refs?

Answer №1

To prevent reference issues, utilize angular.copy function to break the reference chain instead of passing by reference.

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

Tips for sending multiple values as a unified object using Javascript and Ajax

Currently, I am new to javascript and MVC. I am developing a sample application with a sign-up page where I am using ajax for the process. The code snippet below shows my current implementation: function create() { var user_name = $("#txtUser").val(); ...

The styles of a jQuery Mobile listview aren't updating properly when the list items are emptied and then dynamically re-created

When I have a listview that dynamically creates its list items using JavaScript code, everything works perfectly the first time the code runs. However, upon subsequent executions, the list is generated correctly but loses the jQuery Mobile styling. Despite ...

Ways to change user input into a string and locate the position of the first two characters

I'm new here and haven't found a specific answer to my question, so I apologize if I'm not following protocol. My question is about converting text from a form input into a string and extracting a substring from that text. For example, if ...

What is the best way to continuously write multiple lines to a text file within a loop?

As I work within a JavaScript function, my goal is to input a list of events and write text to a file for each event. The script provided looks correct: // Code within another function events.map(event => { const start = event.start.dateTime || ...

Utilizing Numerous Textures within a PointCloud with Three.js

Currently, I am experimenting with implementing multiple textures in a single PointCloud using a ShaderMaterial. To achieve this, I am passing a texture array to the shader along with texture index attributes and selecting the appropriate texture to use in ...

What causes the promise to fail when executed outside of the loop?

I have been working on adding fusionCharts dynamically to an AngularJS page. I load chart data into a model object, and while the charts do display, they show "No data to display" content. My app.js: (function () { var modelListOfCharts = ["1", "4", "5" ...

What steps can I take to stop forms from being automatically submitted when loaded through Ajax in my Laravel 8 application?

I developed a blogging application using Laravel 8 and I am currently enhancing it by implementing comment replies with jQuery (v3.5.0) AJAX. In the file comment-form.blade.php, here is the structure: <div class="form-wrapper"> <div c ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

The sequence of ngRepeat and directives execution

When working with an Angular directive that includes an ngRepeat element, it seems like the ngRepeat execution occurs after the linking of the containing directive. Is there a way to set up a response mechanism ($watch, $observe, etc) that will trigger af ...

browsing through a timeline created using HTML and CSS

I am currently working on a web project that involves creating a timeline with rows of information, similar to a Gantt chart. Here are the key features I need: The ability for users to scroll horizontally through time. Vertical scrolling capability to na ...

Uploading data through Ajax and integrating it into the database

I am in the process of creating a form to add a new team to our database. The goal is to insert all relevant team information into the database and simultaneously upload the team's logo to the appropriate directory within our system. <form ...

Component nesting is not supported; cannot render a component inside a

I've set up a simple Vue application within Rails, but I am encountering an issue: hello_vue.js: import Vue from 'vue/dist/vue.esm' import TurbolinksAdapter from 'vue-turbolinks' Vue.use(TurbolinksAdapter) import CollectionSet f ...

Is there a way to incorporate a computed value into a table prop while working with Element UI?

In my frontend development, I am utilizing vuejs along with element ui. I am faced with the task of rendering a table that includes dates in unix format. To make these dates more user-friendly, I have incorporated moment.js to convert them into a readable ...

What is the best way to arrange an array of identical objects based on a specific sub property?

Here's an array of items to work with: myArray = [ { someDate: "2018-01-11T00:00:00", name: "John Smith", level: 5000 }, { someDate: "2017-12-18T00:00:00", name: "Jane Doe", level: 1000 }, { ...

Having trouble getting the Basic Drag and Drop JavaScript code to function correctly?

Apologies, my English skills are not the best! I attempted to implement a basic JavaScript, HTML, and CSS drag-and-drop feature but it doesn't seem to be working correctly. Can someone please take a look at the website to see what is going wrong? ...

The import map is not being recognized by Supabase Edge Functions when passed in the command `npx supabase functions serve`

My situation involves two edge functions, namely create-payment-link and retrieve-payment-link. However, they are currently utilizing the import map located at /home/deno/flag_import_map.json, rather than the import_map.json file within the functions folde ...

Utilize vue.js to save the components of an object

data() { return: { user: {}, userName: "", userAge: "" } }, methods: { saveUserName: function() { this.userName = this.newUserName; this.$refs.userNameModal.hideModal(); this.$ ...

How is it possible to retrieve an object property using an array?

I would love to hear an explanation of the behavior exhibited by this code snippet: let obj = {a:1, b:2} let i = ['a'] console.log(obj[i]) >> 1 Isn't it interesting how even an array can be utilized to access a property within an obj ...

After 30 seconds of inactivity, apply the CSS once, then remove it before repeating the process

I've got a unique little CodePen with an animation that I want to execute only if the user hasn't clicked on the <div class="someDiv"> for 30 seconds. My question is, can someone guide me in the right direction so that when someone doesn&a ...

Is there a way to capture an error message in the JSON fetch response?

Here is the code snippet to consider: fetch('https://api.flickr.com/services/rest/?method=flickr.photos.search' + '&api_key=thiskeyshouldgivemeanerror&text=dog&format=json' + '&per_page=24&nojsoncallbac ...