Remove the dropdown menu in real time, ensuring that only the most recent one is

Although the example may seem unusual, I am deliberately recreating a real problem to find a solution.

When I click on a button, it generates 3 dynamic dropdowns based on a list of animals. My issue is that I want to delete a selected item, but it always deletes the last one. What can I do to solve this?

<div ng-repeat='item in dropdown track by $index'>
   <select class="form-control animal" ng-model='MyAnimals[$index]'  
  ng-options="opt as opt.animal for opt in aAnimals">
     <option value="">Select an animal</option>
  </select>
    <button type="button" ng-click='delete(item)'  class="btn btn-default">
        delete    
    </button>
</div>
<button ng-click='add()' >generate</button>

$scope.obj = {}
$scope.aAnimals=
[
 { "animal": "cat"},  //first dropdown
 { "animal": "dog"},  //second dropdown
 { "animal": "parrot"}  //third dropdown
]

$scope.MyAnimals = [];
$scope.add=function(){
$scope.dropdown=[];
for(var i in $scope.aAnimals){
 $scope.dropdown.push({ "animal": $scope.aAnimals[i].animal });
 $scope.MyAnimals[i] = $scope.aAnimals[i]; //The model of each Select
 }
}

$scope.delete=function(item){
 var index = $scope.dropdown.indexOf(item);
 $scope.dropdown.splice(index, 1);
} 

http://plnkr.co/edit/gFyj0YHH1WZQ79lDyizS?p=preview

Answer №1

Your MyAnimals scope does not update after deleting the correct item. Make sure to also delete the item from the MyAnimals scope to ensure proper synchronization.

<html ng-app="app">
 <head>
  <script  src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script data-require="angular.js@*" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
  <script>
    var SidController = function($scope){
      $scope.obj = {}
      $scope.aAnimals=
       [
        { "animal": "cat"},  //first dropdown
        { "animal": "dog"},  //second dropdown
        { "animal": "parrot"}  //third dropdown
     ]
     $scope.MyAnimals = [];
     $scope.add=function(){
      $scope.dropdown=[];
      for(var i in $scope.aAnimals){
        $scope.dropdown.push({ "animal": $scope.aAnimals[i].animal });
        $scope.MyAnimals[i] = $scope.aAnimals[i]; //Model for each Select
       }
     }

     $scope.delete=function(item){
       var index = $scope.dropdown.indexOf(item);
       $scope.dropdown.splice(index, 1);
       $scope.MyAnimals.splice(index, 1);
     } 
 };
 SidController.$inject = ['$scope'];
 angular.module('app', []).controller('SidController', SidController);

</script>
</head>

<body ng-controller = "SidController">
  <div ng-repeat='item in dropdown track by $index'>
     <select class="form-control animal" ng-model='MyAnimals[$index]'  
        ng-options="opt as opt.animal for opt in aAnimals">
        <option value="">Select an animal</option>
     </select>
     <button type="button" ng-click='delete(item)'  class="btn btn-default">
     delete    
     </button>
  </div>
  <button ng-click='add()' >generate</button>
</body>

Answer №2

To properly delete an item, remember to include $index as an argument in the delete function in your HTML code.

ng-click='delete($index)'

By passing the index, you won't need to retrieve it within the delete function. Additionally, when deleting items from a list generated with ng-repeat, make sure to remove both $scope.dropdown and $scope.MyAnimals. If you only remove the dropdown, the value will still be based on the MyAnimals scope.

Therefore, your delete function should look like this:

$scope.delete=function(index){
   $scope.dropdown.splice(index, 1);
   $scope.MyAnimals.splice(index, 1);
} 

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

What are the potential drawbacks of importing a namespace and a child module together? For example, using `import React, { Component } from ...`

Collaborating with some colleagues on a React project, I began by importing React and constructing my class like this: import React from 'react' Class MyComponent extends React.Component But then they suggested that I also import Component sep ...

Using the power of ReactJS, efficiently make an axios request in the

After familiarizing myself with Reactjs, I came across an interesting concept called componentDidUpdate(). This method is invoked immediately after updating occurs, but it is not called for the initial render. In one of my components, there's a metho ...

What is the best way to convert a document.getElementById(id) element into a jQuery object?

It's surprising that no one has asked this question before: When I create elements using the following code: document.getElementById(id).innerHTML = (a string with id's in it); for example. I want to use jQuery to update the CSS of these dynam ...

I'm noticing my table collapsing as I move around the div elements - any idea why this is happening

A challenge I am facing is creating a dynamic table where users can drag and drop colored boxes with animated transitions. While it mostly works well, sometimes the table collapses inexplicably. Here are steps to reproduce the issue: Move 100 - 400 Move 1 ...

What method can be used to incorporate expressions into Handlebars partials when dealing with parameters?

Is it possible to include expressions in partials parameters? I am trying to achieve something similar to this: {{> myPartial greeting=(i18n.greeting + "my text") }} ...

symfony submit form without sending request

I'm trying to make a request without using a submit button, only by selecting an option. So far, I've attempted to achieve this using JavaScript but haven't had any success. Here's my form code: $form = $this->createFormBuilder() ...

Can you provide a list of factors that influence coverage? Additionally, is there a specific algorithm available for calculating

As part of my Angular project, I am currently focusing on writing unit test cases using the Jasmine Framework and Karma. To ensure thorough testing coverage, I am utilizing Coverage-html (Istanbul). When it comes to coverage, there are several important t ...

Pusher authentication issue: socket ID not defined

I am currently facing an issue while trying to establish a private channel for users to transmit data to my node.js server. Upon making the request, I encounter an error where pusher:subscription_error is returned with the error code 500. Upon checking my ...

Retrieve all instances of a key-value pair within an object that share the same key

Here is some JSON data: [{"name":"David","text":"Hi"},{"name":"Test_user","text":"test"},{"name":"David","text":"another text"}] I am l ...

How to access an element through the router-outlet in Angular 6?

<side-navigation [navigationTitle]="navTitle"></side-navigation> <router-outlet> </router-outlet> Within my project, I have a navigation bar located in the root component. I have set up [navigationTitle] as an @Input Decorator wit ...

What is the best way to create a dynamic information page using both V-for and V-if in Vue.js?

Hey everyone, I recently attempted to set up this layout: https://i.sstatic.net/WbcBX.png This company offers a variety of services grouped into different categories, each containing sub-options and specific details. This is how my JSON data is structur ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...

Unable to conceal the scrollbar while keeping the div scrollable

I've been attempting to implement the techniques outlined in the guides on this site, but I'm encountering difficulty hiding the scroll bar while still maintaining scrolling functionality! My current approach involves setting the parent as relat ...

Acquiring the asset within the controller

Having trouble accessing my service within the controller. This project was generated with the latest yeoman which handles template creation and file merging during build. Whenever I make changes, Angular stops working without displaying any errors in the ...

What improvements can I implement to enhance the clarity and functionality of this form handler?

As a beginner working on my first Next.js app, I'm facing some challenges that seem more React-related. My app allows users to add and edit stored food items and recipes, requiring me to use multiple submit form handlers. Each handler involves: Che ...

Efficiently handle user authentication for various user types in express.js with the help of passport.js

Struggling to effectively manage user states using Passport.js in Express.js 4.x. I currently have three different user collections stored in my mongodb database: 1. Member (with a profile page) 2. Operator (access to a dashboard) 3. Admin (backend privi ...

`meteor.js and npm both rely on the fs module for file

I'm feeling a bit lost, as I need to use the fs package with Meteor.js framework. Starting from meteor version 0.6 onwards, I know that I should use Npm.require in the following way: var fs = Npm.require('fs'); However, when I try this, a ...

What is preventing my function from retrieving user input from an ngForm?

I'm currently working on my angular component's class. I am attempting to gather user input from a form and create an array of words from that input. The "data" parameter in my submit function is the 'value' attribute of the ngForm. Fo ...

Issues encountered while utilizing Bliss as the template engine in NodeJS/Express

Seeking assistance in transitioning from Jade to Bliss as the template engine for a basic Express web application on NodeJS. Here is the code snippet from app.js: var express = require('express'), routes = require('./routes'), ...

Link together a series of AJAX requests with intervals and share data between them

I am currently developing a method to execute a series of 3 ajax calls for each variable in an array of data with a delay between each call. After referring to this response, I am attempting to modify the code to achieve the following: Introduce a del ...