You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS中excluir函数无法删除列表项问题求助

问题排查与修复方案

我帮你找出了excluir()函数完全失效的几个关键问题,现在逐一说明并给出修复后的完整代码:

1. 拼写错误:lenght → length

你在循环里把数组的长度属性拼写成了lenght,正确的拼写是length。这个错误会导致循环根本无法执行——因为produtos.lenght是undefined,循环条件i < undefined永远不成立,函数自然没有任何反应。

2. 判断条件错误:produtos.id → produto.id

函数参数是produto(你要删除的目标项),但你在判断匹配项时写成了produtos.id(整个数组的id属性,这显然不存在)。正确的逻辑应该是对比循环项的id和传入的目标项id,也就是produtos[i].id === produto.id。

3. 循环未终止(可选优化)

当找到匹配项并执行splice删除后,数组长度会立刻变化,此时应该终止循环,避免后续不必要的遍历,也能防止数组索引错乱。

4. 链接默认行为干扰(可选优化)

原代码里的<a href=""点击后会触发页面跳转(回到顶部或刷新),可能干扰Angular事件的执行。可以改成<a href="#",或者添加ng-click="$event.preventDefault()"来阻止默认行为。


修复后的完整代码

<!DOCTYPE html>
<html ng-app="produtosApp">
<head>
<title>Desenvolvendo Aplicações Web com AngularJS e Java</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body ng-controller="ProdutosController">
<!-- Cadastro -->
<form>
<h1>Cadastro</h1>
<label for="codigo">Código: </label>
<input id="codigo" name="codigo" type="text" ng-model="produto.id"/>
<br>
<label for="descricao">Descrição: </label>
<input id="descricao" name="descricao" type="text" ng-model="produto.descricao"/>
<br>
<label for="preco">Preço: </label>
<input id="preco" name="preco" type="text" ng-model="produto.preco"/>
<br>
<br>
<button ng-click="salvar(produto)"> Salvar </button>
</form>
<!-- Tabela de Preços -->
<h1>Tabelas de Preços</h1>
<table>
<thead>
<tr>
<th>Código</th>
<th>Descrição</th>
<th>Preço</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="produto in produtos track by $index">
<td>{{produto.id}}</td>
<td>{{produto.descricao}}</td>
<td>{{produto.preco}}</td>
<td><a href="#" ng-click="excluir(produto)" >[Excluir]</a></td>
</tr>
</tbody>
</table>
<script src="js/angular.min.js"></script>
<script>
var app = angular.module('produtosApp', []);
app.controller('ProdutosController', function($scope){
var produtos = [{
id: 1,
descricao: 'Arroz',
preco: 2.50
}, {
id: 2,
descricao: 'Feijao',
preco: 3.50
}];
$scope.produto = {};
$scope.produtos = produtos;
$scope.salvar = function(produto) {
produtos.push(produto);
$scope.produto = {};
};
$scope.excluir = function(produto) {
// 修复拼写错误:lenght → length
for(var i = 0, length = produtos.length; i < length; i++){
// 修复判断条件:produtos.id → produto.id
if(produtos[i].id === produto.id){
produtos.splice(i, 1);
// 找到匹配项后终止循环,避免数组长度变化引发的问题
break;
}
}
};
});
</script>
</body>
</html>

内容的提问来源于stack exchange,提问作者Remo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:27:07