Leveraging the push method within AngularJS

Hello, I am currently working on setting up an eCommerce shop using Angular. Below is the code snippet I am using:

var shopApp = angular.module('shopApp', ["slugifier"], function() {});

   controllers.productController = function($scope,FetchFactory) {

     $scope.fetchProducts = function(offset) {
        FetchFactory.items.fetchItems(offset).then(function(data){
        $scope.products = data;
    });
  }
  var activeAttrValue = 0;
  var activeAttrUnit = 0;
  var activeAttrId = 0;
   $scope.add_to_cart() = function(index){
        var newProd = [];
        newProd = $scope.products[index]; // $scope.products have products json
        newProd.quantity = 1;
        newProd.attr_id = activeAttrId;
        newProd.attr_value = activeAttrValue;
        newProd.attr_unit = activeAttrUnit;
        $scope.cartProducts.itemlist.push(newProd);
        $scope.cartProducts.total_items++;
        $scope.cartProducts.total_price += parseInt(newProd.price);
   }
 }
 shopApp.controller(controllers);

I have created a factory that fetches product JSON after an AJAX request. I use ng-repeat as "product in products" to display all products in my HTML and have implemented a shopping cart where added products are displayed using ng-repeat of "cartProduct in cartProducts.itemlist track by $index". Each product has attributes like color, size, weight, etc. When an attribute is selected, its value (e.g., weight) and unit (e.g., kg) are stored in global variables activeAttrValue and activeAttrUnit. When 'add to cart' is clicked, these values are stored in cartProducts.

Problem: When multiple attributes of the same product are selected and added to the cart, only the last added product and attributes are being included. This results in an error message in the console:

 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.16/ngRepeat/dupes?p0=cartProduct%20in%20cartProducts.itemlist&p1=object%3A006

Upon logging $scope.cartProducts.itemlist in the console, I noticed that the attributes of both products are showing the same values.

I hope this explanation clarifies the issue at hand.

Answer №1

When using Angular, you may encounter an issue where duplicated elements are not allowed in ng-repeat loops. To resolve this issue, you can include a "track by" statement within your ng-repeat directive.

For instance, if you have a list of numbers with duplicate values:

<div ng-repeat="value in [1, 1, 1, 2, 2] track by $index"></div>

For further information and troubleshooting tips, refer to the specific URL related to your error

Answer №2

Use the following code:

ng-repeat="cartProduct in cartProducts.itemlist track by $index"
.

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

When attempting to add an item to an array within a sub-document using Mongoose and MongoDB, the error message "Property 'messages' not found" is returned

I am working with four different models: teacher, student, teacherMessageSchema, and studentMessageSchema. The teacherMessageSchema is a subdocument within the 'teacher' model under the messages: [teacherMessageSchema] property, while the student ...

Manipulate a deeply nested JSON object in JavaScript by iterating through it and constructing a new data

Struggling to rearrange complex JSON data (data1) into a more organized format (data2). Progress has been slow. data1 is created by scanning a parent directory (recipes) for html files. data2 is the desired output structure using data1, where content wit ...

The last javascript file that was included has been overlooked

When using jqplot, I noticed that the last included plugin is being ignored. If I switch their positions, the first to last one works while the last one does not. There are no errors in the console to indicate what might be going wrong. Moving the canvasOv ...

Tips for configuring Webstorm to automatically change double quotes to single quotes when reformatting source code

After using cmd + alt + l in Webstorm to format my JavaScript code, I noticed that double quotes are used instead of single quotes. How can I configure Webstorm to automatically change the double quotes to single quotes in my code? ...

When using electron-build, the node-adodb encountered an error stating: 'Failed to spawn C:WINDOWSSysWOW64cscript.exe'

Utilizing node-adodb.js for reading .mdb files with the following code: const db = require('node-adodb') ipcMain.on('query', (e, p) => { if (!p) return appendFileSync('a.log', new Date().getTime() + ' ' + p.t ...

Implementing an asynchronous task queue in AngularJS

I came across this JSFiddle example where three consecutive calls are made to a service function, simulating $http Request interceptor function which returns a promise. The current code does not wait for the previous call to finish before making the next o ...

Execute a JavaScript function prior to initiating an AJAX request

To streamline the process of making AJAX calls in my .NET project, I have developed a function called checkConnection that checks for internet connectivity before each call. However, currently, I am manually calling this function on every button click that ...

Guide to displaying or hiding elements based on the number of selected checkboxes

When only one checkbox is checked, all buttons in the head-btn class should be displayed. By default, only the add folder and upload buttons are shown. If a user selects two checkboxes, the share button should be hidden. If they uncheck one of the checkbo ...

What is the process by which React loads and runs JSX content?

What is the method used to identify and handle JSX code? <script src="src/main.js" type="text/babel"></script> ...

The challenge of Cross-Origin Resource Sharing with AjaxSubmit compared to a traditional Ajax request

My dilemma involves two applications interacting on Google's App Engine, each operating within its own domain. To enable communication between them, I have successfully implemented CORS in Python using the following code: self.response.headers.add_he ...

Creating an onchange event in CodeIgniter for dynamically generated select boxes within a view script

As a beginner with codeigniter, I am seeking some assistance. Within my controller, I retrieve data for both options and suboptions, then load the respective view using the code below. The view essentially generates a table consisting of select boxes passe ...

SweetAlert.js does not function properly within a custom AngularJS directive

When creating a list to display in a modal, I utilized directives for the modal implementation. (I actually didn't write these directives myself) Within the list, each item features two buttons - one for editing the name and the other for deleting t ...

Processing MongoDB elements in NodeJS by retrieving them and appending them to a list or array for further processing

Currently, I am involved in a full stack project that requires fetching stock data from mongodb and performing algorithms on specific information. Here is an illustration of the JSON object stored in mongodb: [{ _id: 5e11d67abf05f3d00d56b801, LUNA: { ...

selectize.js typescript: Unable to access values of an undefined object (reading '0')

I've been working on incorporating selectize.js into my project using webpack and typescript. After installing selectize.js and the necessary types, I added the following to my code: yarn add @selectize/selectize yarn add @types/select2 Within my c ...

Focus automatically on an input component when the value in the Vuex store is updated in Vue

Here's the code snippet from my component: //template <v-select ref='ItemSearchSelect' :options="options"></v-select> ... //script created: function () { this.$store.subscribe((setFocusSearch, state) => { ...

What is the proper method for invoking a function when an HTTP request is made, whether it

Forgive me for asking what may seem like a silly question, but I am new to working with the backend. I am currently developing an AngularJS app using Express/Node and I am attempting to implement PayPal (using the Node.js SDK). My goal is to call the pay ...

What is the best way to distinguish between inline javascript and dynamically created content in Express/Node.js?

I've encountered a bit of a noob-question despite having a few years of experience in web development. Despite searching Programmer Stack Exchange and Google, I haven't found an answer, so here goes. Currently, I'm working with the Express ...

Struggling with implementing a materialize modal?

I am encountering a problem with Materialize. This time, I am trying to create a modal div, but it doesn't seem to be working. The button is created, but when I click on it, nothing happens. I have made sure to link all the necessary Materialize files ...

Problem with ng-include in ng-view templates

Directory Layout: --app --partials --navbar.html --submit --submission.html index.html Using ng-include in submission.html: <ng-include src="'app/partials/navbar.html'" ></ng-include> However, the navbar does not displa ...

Exploring the use of $ in the outcome of a json for jQuery autocomplete functionality

Trying to implement auto complete functionality. Here is the URL I need to read JSON from: http://openscan.addi.dk/2.0/?action=openScan&field=phrase.title&lower=hest&limit=10&outputType=json After receiving the result, I'm attempting ...