including identical item in the array

    <!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body>

<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
    $scope.products = ["Milk", "Bread", "Cheese"];
    $scope.addItem = function () {
        $scope.errortext = "";
        if (!$scope.addMe) {return;}

            $scope.products.push($scope.addMe);

    }
    $scope.removeItem = function (x) {
        $scope.errortext = "";
        $scope.products.splice(x, 1);
    }
});
</script>

<div ng-app="myShoppingList" ng-cloak ng-controller="myCtrl" class="w3-card-2 w3-margin" style="max-width:400px;">
  <header class="w3-container w3-light-grey w3-padding-16">
    <h3>My Shopping List</h3>
  </header>
  <ul class="w3-ul">
    <li ng-repeat="x in products" class="w3-padding-16">{{x}}<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span></li>
  </ul>
  <div class="w3-container w3-light-grey w3-padding-16">
    <div class="w3-row w3-margin-top">
      <div class="w3-col s10">
        <input placeholder="Add shopping items here" ng-model="addMe" class="w3-input w3-border w3-padding">
      </div>
      <div class="w3-col s2">
        <button ng-click="addItem()" class="w3-btn w3-padding w3-green">Add</button>
      </div>
    </div>
    <p class="w3-padding-left w3-text-red">{{errortext}}</p>
  </div>
</div>

</body>
</html>

i have come across this code on w3schools website. The issue I am facing is that when adding a product that already exists in the list, it does not get added again to the list or array.

Answer №1

Although the values are being added to the array, the ng-repeat directive prevents duplicates from appearing in the DOM. To display duplicates, you can utilize track by $index.

ng-repeat="item in products 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

How to interact with the parent controller when including HTML using ng-include

I am trying to call a function in a controller from an ng-included HTML file that includes a directive with its own template. For example, the parent HTML template has this controller: <div ng-controller="profileCtrl"> <div ng-include src="p ...

Error encountered when WebDriverIO attempted to connect to Appium due to a lack of compatible capabilities

I'm currently facing an issue while attempting to link my virtual Android Device through Appium with my Webdriverio script for the purpose of automating some testing tasks. Here are the capabilities that I have set: capabilities: [{ // N ...

How to choose the option in one select box based on the selection in another, and vice versa

How can I dynamically select options in one select box based on the selection of another, and vice versa? I am using Ajax to redirect to a query page. while($result = mysql_fetch_assoc($query1)) { echo "<option value=".$result['username' ...

Steps for organizing a list based on the number of clicks

I've created an HTML list with images of political party logos. Each logo is a grid item that can be clicked on. I want to sort the list based on the number of clicks each logo receives, essentially ranking them by popularity. However, I'm not su ...

What is the best way to save a PDF from within a frame using JavaScript and an HTML5 <embed> tag?

I'm looking for assistance with a script for my website that dynamically generates a PDF after the user makes selections in one of the frames. The website uses the HTML5 tag to display the PDF file. Can anyone provide guidance on a script that can: ...

An empty array is being returned by the Model.find() method after sorting

let query = Tour.find(JSON.parse(queryStr)); if (req.query.sort) { query = query.sort(req.query.sort);//a string 'ratings' } const tours = await query; res.status(200).json({ status: 'success', requestedAt: req.requestTime, ...

Swap out a div identifier and reload the page without a full page refresh

I am interested in learning how to dynamically remove a div id upon button click and then add it back with another button click to load the associated CSS. The goal is for the page to refresh asynchronously to reflect these changes. So far, I have successf ...

Is it possible to determine if an AJAX request is still ongoing when a user returns to a webpage using jQuery or JavaScript?

Users on a specific page must click a 'generate' button to create details for a record. When the button is clicked, an ajax request is triggered to generate the record, which may take some time. $("#generate_record_button").on("cl ...

Hide the popup menu when the user clicks outside of it

I am presenting the following code <!DOCTYPE html> <html> <head> <title>GalacticCraft</title> <link rel="stylesheet" type="text/css" href="style.css" /> <link rel="shortcut icon" type="image/png" href="fa ...

Using an external filter within the ng-grid component

Currently, I am facing a challenge with implementing filter functionality in my table using three search fields - name, target, and reach. The first two filters are working well, but the last one needs to filter by lower-than or higher-than comparison. To ...

Navigating AJAX Pages - Maximize the Potential of #home and Other Sections

I am working on creating AJAX pages using a tutorial I found on Tutorialzine. The script I am using loads pages using AJAX but it requires specifying the page number in the URL like http://example.com/#page1 or http://example.com/#page2. Is there a way t ...

Utilizing Google Maps to display an infowindow upon clicking a location from a geojson file

I want to implement info windows that pop up when markers on a map are clicked. I used the sample code provided by Google (below) to create a marker map from geojson files dragged and dropped into the window. My goal is for the info windows to show text ta ...

Struggling to import MUI components from node modules in your React JavaScript project using Vite? Discover why autosuggestion isn't getting the

Encountering a dilemma with autosuggestion in Visual Studio Code (VSCode) while attempting to import MUI (Material-UI) components from node modules in my React JavaScript project built with Vite. The autosuggestion feature is not working as intended, causi ...

The process of using Jest to test whether a React component correctly renders a list

I've been diving into the world of unit testing and recently developed a small React application that showcases a list of Pokemon. My goal is to create a unit test that verifies if the list renders correctly. However, when I generate a snapshot, it on ...

Unable to activate slideToggle due to malfunctioning links

When using the slideToggle function, I encountered an issue where the links are not functioning properly. Check out my demo site at the following link: Here is my script: $(".nav li > a").click(function(e) { $(this).parent().siblings().find(&a ...

Unexpected error occurs when modifying HTML5 video source using JQuery on Internet Explorer

Currently, I am working on developing a web application using asp.net, Bootstrap, and JQuery. While testing it on LocalHost, I encountered an issue that needs debugging. The navigation bar of my application has a dropdown menu with links to tutorial video ...

What is the best way to determine if an object.property is defined in Angular 2?

Is there a similar function in Angular 2 to angular.isDefined from Angular 1? I have tried using the safe navigation operator ?., which is only supported in templates. ...

Reset button in AngularJs fails to reset the $error.required message

<div class="form-group"> <input type="text" name="Name" data-ng-model="panNumber" required> <p data-ng-show="loginForm.Name.$error.required && (loginForm.Name.$touched || submitted)" class="error-block">Please make s ...

What is the method for importing jQuery from a local source?

My experience with CDNs has been seamless, but I've run into some issues when trying to use jquery/jquery mobile locally. It seems that certain classes work intermittently, while others don't work at all. The versions I am using are: jQuery - ...

Serialize the elements within an array using JSON.stringify

I'm trying to convert an object into a string, but for some reason it's not working correctly: function httpRequest(url) { this.url = url; this.headers = []; } var req = new httpRequest("http://test.com"); req.headers["cookie"] = "version=1 ...