Struggling to clear items from input field within AngularJS

I'm currently facing an issue where I am unable to delete data from an input field.

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function MyCtrl($scope) {
    $scope.items = [
        {
            name: 'item 1',
            id: '4'
        },
        {
            name: 'item 2',
            id: '3'
        },
        {
            name: 'item 3',
            id: '2'
        },
        {
            name: 'item 4',
            id: '1'
        }
    ];
    
    $scope.delete = function (item) {
        $scope.items.splice($scope.items.indexOf(item), 1);
    }
});
<div ng-controller="MyCtrl">
    <div ng-repeat="item in items | orderBy: 'id'" ng-click="delete(item)">
        <span>
            Hello, {{item.name}}!
        </span>
    </div>
    <input type="text" ng-model="items" />
</div>
<script src="https://code.angularjs.org/1.4.0/angular.js"></script>

To view the JSFIDDLE demonstration, click here.

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

Answer №1

Updated the user interface slightly.

Introduced a button to remove the selected item

Please enter the name of the item you want to remove in the input field

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function MyCtrl($scope) {
    $scope.items = [
        {
            name: 'item 1',
            id: '4'
        },
        {
            name: 'item 2',
            id: '3'
        },
        {
            name: 'item 3',
            id: '2'
        },
        {
            name: 'item 4',
            id: '1'
        }
    ];
    
    $scope.delete = function (item) {
    for(var x in $scope.items){
      if($scope.items[x].name == item){
        $scope.items.splice($scope.items.indexOf($scope.items[x]), 1);
           $scope.toRemove = '' // clear input field after deleting
          }
      }
    }
});
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <div ng-repeat="item in items | orderBy: 'id'">
        <span>
            Hello, {{item.name}}!
        </span>
    </div>
    <input type="text" ng-model="toRemove" />
    <button ng-click="delete(toRemove)">delete</button>
  </div>
</div>
<script src="https://code.angularjs.org/1.4.0/angular.js"></script>

Check out the live demonstration here

Answer №2

Issues in your code

$scope.delete = function (item) {
     $scope.items.splice($scope.items.indexOf(item), 1);
}
The problem lies in trying to fetch the index of an "object" within an array using "indexOf(item)".

Solution:

$scope.delete = function (item) { 
        // Find the position of item in the items array
        position = $scope.items.map(function(e) { return e.name; }).indexOf(item.name);
        $scope.items.splice(position, 1);
        console.log($scope.items);
  }

Check this Plunker for reference

Answer №3

Give this a try, it might align with what you are looking for.

var application = angular.module('myApp', []);
application.controller('myCtrl', function($scope) {
    $scope.items = [
                    {name : 'item1', id : '4'},
                    {name : 'item2', id : '3'},
                    {name : 'item3', id : '2'},
                    {name : 'item4', id : '1'}
                    ];
    $scope.addTextField = function(name){
    $scope.textFiles = name;
    };
    $scope.remove = function(item){
    for (var i=0; i<$scope.items.length; i++){
    if($scope.items[i].name == item){
    $scope.items.splice($scope.items.indexOf($scope.items[i]), 1);
    $scope.textFiles = '';
    }
    }
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl" >
<div ng-repeat="item in items | orderBy: 'id'" ng-click="addTextField(item.name);">
Click here {{item.name}}!
</div>
<input type="text" ng-model="textFiles"><input type="button" value="X" ng-click="remove(textFiles);">
</div>

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

Avoid showing an image when it is outside the div container

Within a single div, I have an assortment of images that are dynamically repositioned using JQuery. $("#"+carElem).css({"left": pos.left+50 +"px"}); I am currently utilizing absolute positioning (although relative positioning yields the same outcome). Is ...

What is the best way to choose the unique identifier of an HTML element inside a for loop in a Django template?

I need help selecting an HTML button that is generated within a for loop in a Django template using JavaScript. How can I assign a unique ID to each button and select it correctly in JavaScript? Currently, all buttons have the same ID within the loop, resu ...

Confirm that only the days of the present month are eligible for selection

I have been given the responsibility of validating a date field that is populated when an invoice is created. The date field consists of a text box and three button objects allowing users to select a date from a calendar, input today's date, or remove ...

I am facing difficulty in incorporating an IP address or URL within an IFRAME in my Cordova Android application

This page does not allow any iframes to load except for the YouTube video URL. When attempting to use any other iframe URL, the following error code is displayed: Error : net::ERR_BLOCKED_BY_RESPONSE In the example below, any URL or IP address fails to l ...

Implementing Ajax to Load Template-Part in Wordpress

Hey there! I'm currently working on enhancing my online store by adding a new feature. What I'd like to achieve is that when a customer clicks on a product, instead of being taken to the product page, the product details load using AJAX right on ...

do not continue loop if promise is rejected in AngularJS

I've attempted multiple methods, but still haven't found a solution to this issue. Within my code, there is a method called iterator that returns a promise; this method runs in a loop x number of times. If the iterator function returns a rejecte ...

Remove the icon disc background from a select element using jQuery Mobile

As I delve into building my first jQuery Mobile app using PhoneGap/Cordova, I have encountered some challenges along the way in getting the styling just right, but overall, things are going well. However, when it comes to working with forms, I hit a roadb ...

angular directive add unique key to DOM element

When I am looping through DOM elements of an Angular component with ngFor, it looks like this: <td> <button class="dropdown-item" [id]="compte_ingroup" href="#"> action </button> </td> My question is: how ca ...

Deciphering the functionality of req.flash()

I'm finding myself confused about how to use req.flash in node.js. For example, I have a .catch block that looks like this: Login function .catch(function(e){ req.flash('errors', 'error here') res.redirect('/') }) ...

Guide to comparing 2 arrays and determining the quantity of identical elements

If an AJAX call returns 2 arrays upon successful execution, the arrays will be different each time but may contain some common elements. For instance: array1 = [x, y, z, a] array2 = [x, y, y, y, x, z, y, z, z] The goal is to determine how many times eac ...

find all the possible combinations of elements from multiple arrays

I have a set of N arrays that contain objects with the same keys. arr[ {values:val1,names:someName},   {values:val2,names:otherName}, ] arr2[   {values:valx,names:someNamex}, {values:valy,names:otherNamey}, ] My goal is to combine all possible c ...

Integrate AngularJS with Laravel using API keys

I am currently developing an application that utilizes Laravel for the backend and AngularJS for the front-end. The user authentication process between the front-end and the API is quite simple, as JSON web-tokens (JWT) are used. This particular tutorial ...

Asynchronous Await Eagerly Anticipates Promise Status: <awaiting

Struggling to implement async/await in an express route and encountering issues. Despite referencing various SO posts, it seems like my implementation is correct. Helpers: module.exports = { facebook: function(userId, token) { return new Promise(re ...

Unable to find any matches when conducting a search through Google Apps Script

After spending days analyzing the code, I am encountering an error that states "uncaught reference error: google is not defined." This issue seems to occur specifically in line 360. Curiously, when inspecting the original code editor, line 360 simply conta ...

Angular: StaticInjectorError(ExplorationEditorPageModule)[Number]

Currently in the process of transitioning oppia's codebase from AngularJS(1.x) to Angular(2+). I recently migrated a service called UtilsService.ts to the following code snippet: import { Injectable } from '@angular/core'; import { downgrad ...

Looking for suggestions on how to bring this idea to life

I'm searching for a solution using JavaScript, jQuery, or Angular. I've created three random arrays like this: for example: (The values are randomly generated from the array ['member', 'medical', 'rx', 'disabi ...

Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with: In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field. I am lo ...

Ways to ensure that v-model does not become "true" or "false" in an input checkbox using Vue

I am currently working on a filter popup that includes a list of checkboxes. By default, some items should be selected and others not selected. I have connected these checkboxes to an object array using v-model. My issue is that when I deselect and select ...

Ensure that an async function's result is resolved before rendering react routes

I've been working on setting up an authentication service in my single-page application using React in the routes file. The goal is to check if a user is trying to access a private path, and verify that the token stored locally is valid. However, I&ap ...

How can I turn off shadows for every component?

Is it feasible to deactivate shadows and elevation on all components using a configuration setting? ...