gpt4 book ai didi

javascript - Angular 杂货 list - 删除单个项目

转载 作者:行者123 更新时间:2023-12-03 07:13:14 25 4
gpt4 key购买 nike

我有一个 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);
}

关于javascript - Angular 杂货 list - 删除单个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36536334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com