What is the best way to toggle a specific div element within an ng-repeat loop?

I have a list of products. When I click on a product, it should be added to the database. If I click on the same product again, it should be removed from the database. I am toggling the wishlistFlag using ng-click. This works correctly for one div element, but for the second div element, it behaves in reverse. For example, if the first product is added and then I click on the second product, the first product gets removed instead of adding the second product.

<div class="hmpal-prprt-post-wdgt hmpal-prprt-wishlist">
    <a href="">
        <span class="prprt-icon"><i class="fa fa-heart" aria-hidden="true" 
            ng-click="WishlistAdd($index,project.propertyId)"></i></span>
        <span>Wishlist</span>
    </a>
 </div>

And here is the Controller code:

a.WishlistAdd = function (index,propertyId) {

    a.wishlistFlag = !a.wishlistFlag;

    var data = {
        wishlistFlag:a.wishlistFlag,
        propertyId:propertyId
    };

    e.createWishLists(data).then(function (result) {
        alert("success");
        alert(JSON.stringify(result));
    }, function (error) {
       alert("error");
       alert(JSON.stringify(error));
    });
}

How can I implement toggling wishlistFlag for different products?

Answer №1

If you only want one product selected in your wish list, consider using the product id instead of a boolean flag. This way, the "selectedProductId" variable in the controller can either be null (if no product is selected) or contain the id of the selected product.

To toggle selection, simply check if the current selected id matches the clicked one.

Assumptions:

  1. When "wishListFlag === true" in the data sent, the product identified by "propertyId" should be added. Otherwise, it should be removed from the database.
  2. Adding a product on the server side will replace any existing selected product.

// Is there a selected product ?
var selectedProductId = null;

a.WishlistAdd = function (index, propertyId) {

    selectedProductId = (selectedProductId === propertyId ? null : propertyId);

    var data = {
        wishlistFlag: (selectedProductId !== null),
        propertyId: propertyId
    };

    e.createWishLists(data).then(function (result) {
        alert("sucesss");
        alert(JSON.stringify(result));
    }, function (error) {
       alert("error");
       alert(JSON.stringify(error));
    });
}

Answer №2

Utilize $index to assign a unique flag to each item in the wishList. Examples of how this can be implemented include:

a.wishListFlag[index]

Answer №3

Keep a record of added propertyIds in an array before saving to the database. Check if the id is already in the array - if it is, remove it from the database and the array. If not, simply remove it from the database.

    var wishList = [];

    a.WishlistAdd = function (index,propertyId) {


        var data = {
            wishlistFlag: wishList.indexOf(propertyId) === -1,
            propertyId:propertyId
        };

        e.createWishLists(data).then(function (result) {

            //add or remove propertyid from whishList
            if(data.wishlistFlag)
                wishList.push(propertyId);

            else
                wishList.splice(wishList.indexOf(propertyId), 1);

            alert("sucesss");
            alert(JSON.stringify(result));
        }, function (error) {
           alert("error");
           alert(JSON.stringify(error));
        });
    }

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

Having trouble displaying an image in your React project?

I'm having an issue with my code where the logo is not displaying, even though it should be in the src -> pages -> images folder. I can't seem to figure out why this is happening. import dress from "./images/dress.png"; const I1 = () => ...

The Arrival of Link: A Countdown Timer

I'm attempting to create a countdown timer that reveals a link after 20 minutes. Currently, this is my progress... <script type="text/javascript"> window.onload = function() { countDown('my_div1', '<a href="cdtl.html" ...

How do I switch languages in Angular?

Is there a way to change the language of my Angular app from English to another language without using localization? I am wondering if Google Translate or any other API can be used for this purpose. ...

Steps for creating a herringbone design on an HTML canvas

Seeking Help to Create Herringbone Pattern Filled with Images on Canvas I am a beginner in canvas 2d drawing and need assistance with drawing mixed tiles in a cross pattern (Herringbone). var canvas = this.__canvas = new fabric.Canvas('canvas' ...

Tips for obtaining response headers

Currently, I am utilizing Angular version 15.0 and retrieving a list of items from the backend (ASP.NET Core 5) with an additional item attached to the header. The GET method in the client-side service is as follows: /** GET Paged commodities from the s ...

Creating a dynamic form that efficiently captures user information and automatically redirects to the appropriate web page

Sorry for the unusual question, but it was the best way I could think of asking. I have come across websites with fill-in-the-blank lines where you can input your desired information and then get redirected to another page. For example: "What are you sea ...

Adding an HTML arrow icon within a button

As I work on creating an HTML email, my aim is to incorporate a right arrow onto an HTML button. To achieve this, I have opted to utilize a special character and apply the transform-rotate property. However, I am facing an issue where the text and arrow a ...

Creating a layout with an image positioned on the left and text on the right within a block using CSS

Can anyone provide guidance on how to design a layout similar to the one shown in this image: https://i.sstatic.net/RYAuA.png? I want the image on the left and text on the right, with responsiveness. Any help would be greatly appreciated. Thank you! < ...

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

The size of objects on canvas is not consistent when loading with fabric.js loadFromJSON

Click here to view the code var canvas = new fabric.Canvas('canvas_1'); var canvas2 = new fabric.Canvas('canvas_2'); var imgObj = new Image(); imgObj.src = "https://gtaprinting.ca/wp-content/uploads/2021/05/blank-t-shirt-front-gre ...

A step-by-step guide on showcasing the content from a textfield onto a dynamic column chart

How can I show the value from a text field in a column chart? I found the code for the chart on this website(). I tried using the code below, but nothing happens. Can someone please assist me? <script> window.onload = function () { ...

Is it possible to execute a URL twice instead of just once in AngularJS?

While developing a web application with AngularJS and Rest Web services, I encountered a problem where the URL is being executed twice instead of just once. I have created a service function for executing the web service API and calling it from the control ...

Eliminating the Controller from the Previous Route Upon Reaching the Next Route

One challenge I'm facing with my Angular application is that when switching from one controller view to another, asynchronous functions initiated in the first view might continue executing even after navigating away. This can lead to unexpected behavi ...

The x-axis is represented by JSON keys, while the y-axis is represented by

I am currently attempting to replicate a graph that was originally made in Excel. Here is the code I have written so far: var data = [ { 'FB':4, 'Mv':4, 'CB':5, 'SL':3, ...

The GET API is functioning properly on Google Chrome but is experiencing issues on Internet Explorer 11

Upon launching my application, I encountered an issue with the v1/validsColumns endpoint call. It seems to be functioning properly in Chrome, but I am getting a 400 error in IE11. In IE v1/validCopyColumns?category=RFQ&columns=["ACTION_STATUS","ACTIO ...

Mobile devices experiencing issues with Bootstrap navbar collapse functionality

When I resize my browser, everything looks fine. However, when I try to access the website from my phone or tablet, it loads the desktop version that is not collapsed properly. Could there be any issues with my HTML code? <nav class="navbar navbar-cus ...

What is the best way to combine elements from different arrays to create a comprehensive listing?

My current function successfully pulls data from another source to create a listing. However, the data I require is spread across multiple arrays, causing some items to be returned as "undefined." At the moment, I am only fetching data from the products a ...

What is the best way to eliminate the blue outline around an image map?

On the landing page, I have a static background image and I've set up a clickable area using an image map. The issue is that when users click on the area, a blue border appears (see image below). I've tried several methods to remove this border b ...

hide content on both desktop and mobile devices

I can't seem to figure out what's wrong here and my mind is blank. I have 2 tables - one for desktop users and one for mobile users. I attempted to hide one using the display none property in my code. .mobile{display: none;} This CSS was mean ...

Dynamic extension of classes in SCSSORExtending classes

When working with Vue, I encountered a situation similar to :style="{ [`--chip-bg-hover`]: hoverColorValue, [`--chip-bg-active`]: activeColor, [`--chip-border-hover`]: borderHoverColorValue, }" Then, i ...