Iron-localstorage in Polymer 2.0 now supports storing and managing two distinct arrays

Looking for help with creating a shopping cart using Polymer. I'm struggling to insert selected data from the template dom-repeat into an array bound to iron-localstorage (e.model.item) and it's not working.

<dom-module id="shop-cart">
<template>
<iron-ajax url="list.json" last-response="{{ListProducts}}" auto>
</iron-ajax>

  <template is="dom-repeat" items="{{ListProducts}}">
     <p style="display:block;width:400px">
        <span>{{item.code}}</span>
        <span>{{item.title}}</span>
        <paper-button raised class="indigo" on-
        click="addProduct">Add</paper-button>
        <br/>
     </p>  

  </template>



 <iron-localstorage name="my-app-storage"
    value="{{Orders}}"
    on-iron-localstorage-load-empty="initializeDefaultOrders"
  ></iron-localstorage>


  <template is="dom-repeat" items="Orders" as="order">
      <div>
        <p>{{order.code}}</p>
        <p>{{order.title}}</p>
      </div> 
  </template>


</template>   

<script>
    class ShopCart extends Polymer.Element {
        static get is() {
            return 'shop-cart';
        }
        static get properties() {
            return {
                Product: {
                    type: String
                         },

                Orders: {
                        type: Array,
                        value() {
                            return [
                                {
                                code:'',
                                title:'',
                                }
                            ];
                        },
                        },
                ListProducts: {
                        type: Array,
                        value() {
                            return [];
                        },
                   }

            }
        }


        initializeDefaultOrders() {
              this.Orders = {
                code:'',
                title:''
              }
           };

        addProduct(e) {  
              this.Product= e.model.item.title;
              this.push('Orders',this.Product);
              this.set('Product','');


        }

        deleteProduct(e) {
            this.splice('Orders', e.model.index, 1);
        }

    }


    window.customElements.define(ShopCart.is, ShopCart);
    </script>
</dom-module>
<shop-cart></shop-cart>

Answer №1

Your method, addProduct(e), should not rely on the data model of ListProducts.

Consider a shopping cart example where the selection (a checked checkbox) is linked to item.selected property.

https://github.com/renfeng/android-repository/blob/master/elements/android-sdk-manager.html#L267-L297

If checkboxes are not ideal, you can use a custom attribute with your button, like selected

This code is specific to Polymer 1.

<paper-button raised class="indigo" on-click="addProduct" selected="[[item.title]]">Add</paper-button>

To retrieve the title of the selected item, include this line:

this.Product= e.target.getAttribute("selected");

For Polymer 2, here is your solution.

https://github.com/renfeng/stackoverflow-question-44534326/commit/b2a4226bd5a1f5da7fa2d5a8819c53c65df7c412

A custom attribute has been suggested for Polymer 2, but it may not be implemented yet. See https://github.com/Polymer/polymer/issues/4457

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

Creating a custom Angular filter to group every 3 items within an iteration into a new div container

When attempting to organize three instances of app-story-preview within a wrapper div using a ngFor loop, I encountered the following code: <ng-template [ngIf]="stories.length > 0" [ngIfElse]="empty"> <cdk-virtual-scroll-viewport [itemSize ...

Memory problem with rendering text on a 2D canvas in ThreeJs

How can I optimize my code for rendering nearly 200 texts using 2D canvas rendering? The current method is consuming a lot of memory. Is there a way to reuse the canvas element? Here is a snippet of my current implementation: var goalCanvas = document.c ...

Is it necessary for each React component to have its own individual stylesheet?

Looking for some advice on React as a newbie here. I'm wondering whether each React component should have its own stylesheet. For instance, if I have my main App component that gets rendered to the browser, is it sufficient to include a CSS file the ...

We were unable to locate the module '@reactflow/core' or its associated type declarations

After forking reactflow, I attempted to make some modifications but encountered a type error even without making any changes. https://i.sstatic.net/EyTZE.jpg My next step was to try "pnpm i @types/reactflow," but it did not resolve the issue. ...

Retrieve the array if it contains the ID in Mongoose

It's a bit of a tricky situation. I initially thought I could use $in for the query, but it turned out that it wasn't in the place I expected. Here's my schema: var gameSchema = new mongoose.Schema({ state: { type: String, ...

Dealing with Memory Leakage in C Programming

Currently working with GTK and struggling with the malloc() function. Valgrind is showing a memory leak, so I'm wondering what I'm doing wrong. Initially, I created a three-dimensional array by defining a pointer to a pointer to a pointer to a GT ...

The split() function returns a string that remains unaltered and intact, without any

I am attempting to separate this string: 120,00 m² into two distinct parts like this: 120 m² This is the code I have been using: var test = jQuery('#wpsight-listing-details-3 .span4:nth-child(4) .listing-details-value').html(); var pa ...

Blur images on parent div when hovering using javascript

After some extensive searching, I came across a few helpful explanations on how to achieve my desired outcome. By combining them, I was able to get everything working smoothly with the hover effect over the image itself. However, when I attempted to trigge ...

Guide on sending two dynamically generated select box values through ajax in order to retrieve values for a third select box

I am currently working on a task where I need to populate the 3rd select box based on the selections made in the first two select boxes, which have dynamic values. Below is the jQuery ajax code snippet that I have written (Please note that this code curre ...

Implementing asynchronous loading of an image onto a webpage using JavaScript

Is it possible to asynchronously load an image specified in the src attribute of an HTML image tag? I am trying to invoke a Java class using an image src tag, but I want this to happen asynchronously without affecting the current functionality of the web ...

Troubleshooting Confluence's "Hello World" Macro: Issues with NPM Installation and Startup

I am in the process of creating my very first confluence macro, and I am following the guidelines provided at this link: Right now, I am facing some difficulties with steps 2 and 4; specifically NPM install and NPM start: Encountered the following errors ...

Understanding the functionality of a loop with a nested array

I'm currently trying to comprehend how this array functions within a loop for (int answer=0; answer<responses.length; answer++) { ++frequency[responses[answer]] } The 'Frequency' array is initialized as follows: int [] frequency = new ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

I am struggling to locate the template for my Angular UI modal

I recently developed an app and tried using UI modal, but encountered an issue where the modal function couldn't locate the HTML template. I was able to log messages inside the function but was unable to open a modal view. var app = angular.module(& ...

Adding a Javascript file to the requirejs-config.js file in Magento 2

How can I properly load a JS file using requirejs? <script type="module" src="https://unpkg.com/@google/model-viewer/dist/model-viewer.min.js"></script> Here is my requirejs-config.js file: var config = { paths: { mod ...

Angular 12 app does not have Express server searching for static files

Context I am in the process of transferring an Angular application to a GKE cluster. Unfortunately, due to company policy, the base docker image I am required to use does not support the installation of new software such as shell or Angular CLI commands l ...

Angular 1.5 component using HTTP GET

Trying to utilize a 1.5 component with AngularJS has presented some challenges for me. I have a service that fetches my JSON file using $HTTP and returns a promise. In the controller of my component, I resolve the promise and assign it to a value using thi ...

ReCaptcha: connecting to the TextBox's OnKeyDown event using script

I've been figuring out how to integrate ReCaptcha, ASP.NET, and Gaia Ajax. It was a bit of a challenge to use the ReCaptcha AJAX APIs with Gaia to fetch the data from the recaptcha_response_field text box in an AJAX postback through a patch. This was ...

Is it possible to leverage both functions and variables within the ng-options expression in Angularjs?

I am faced with a situation where I have 2 select boxes. The first one is used to choose the user type (such as groups or individual), and the second one displays the options based on the selection made in the first box. I was wondering if it is possible t ...

A guide on utilizing jQuery to multiply multiple arrays

Form Image <div class="form-inline form-group"> <div class="input-group form-group"> <input class="form-control" type="text" name="budget-value1[]" size="3" placeholder="10"> <label>hrs x</label> <input ...