Angular Grocery List-删除单个项目

Angular Grocery List - Delete Single Item

本文关键字:单个 项目 删除 List- Grocery Angular      更新时间:2024-04-06

我有一个Angular应用程序,我正在努力使其正常工作。显然,只有一行代码可以使它工作,但我不知道它是什么。我仍在学习Angular,无论如何我对Javascript都不太擅长。我这样做是为了将输入的任何内容都添加到列表中。但当我点击一个按钮删除一个项目时,它只会删除所有项目。我能做些什么来修复它?

  <body ng-app="myApp">
        <div ng-controller="GroceryController">
            <header>
                <h1>Matt's Grocery List</h1>
                <div>
                    <form ng-submit="addItem()">
                        <div>
                            <input type="text" ng-model="newItem" placeholder="New things">
                            <button type="submit">Save</button>
                        </div>
                    </form>
                </div>
            </header>
            <section id="list">
            <p>"{{ newItem }}"</p>
            <div>
                <h4>{{ groceries.length }} total items</h4>
                <table>
                    <tr ng-repeat="gro in groceries">
                        <td>{{gro}}</td>
                        <td>
                            <button class="remove" ng-click="removeItem(gro)">&times;</button>
                        </td>
                    </tr>
                </table>
            </div>
            </section>
        </div>
    </body>
var app = angular.module('myApp', []);
app.controller('GroceryController', function($scope){
    $scope.groceries = ['Nails', 'Pipe', 'Wood'];
    $scope.addItem = function() {
        $scope.groceries.push($scope.newItem);
        $scope.newItem = '';
    }
    $scope.removeItem = function(item) {
        var idx = $scope.groceries.indexOf(item);
            $scope.groceries.splice(idx.l);
    }
});

我这里有一把JSfiddle,但实际上我无法让它在那里运行。当我尝试在浏览器中执行时,它运行得很好。也许你可以让它运行,然后你就可以解决问题了。我真的很感激!谢谢

https://jsfiddle.net/bt08rbqt/

拼接方法中存在错误。按以下方式使用-

$scope.removeItem = function(item) {
    $scope.groceries.splice($scope.groceries.indexOf(item),1);
}