gpt4 book ai didi

javascript - 如何正确从表中删除对象?

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

我在 Controller 中创建了删除功能,但它无法正常工作。它总是删除数组表中的最后一个对象。可能是什么问题?

谢谢!

app.js

table.controller('TodoCtrl', function ($scope, $http, $localStorage) {
$scope.$storage = $localStorage.$default({
"extraTodo": [],
"todos":[
{ "id":1,"text":"learn AngularJS", "color":"red", "progress":30},
{ "id":2,"text":"build an AngularJS app", "color":"blue", "progress":30},
{ "id":3,"text":"learning Python", "color":"red","progress":70},
{ "id":4,"text":"build an Python app", "color":"blue", "progress":80},

]

});

$scope.extraTodoData = $localStorage.extraTodo;
$scope.todoData = $localStorage.todos;

$scope.Delete = function (del) {
console.log(del);
var result = confirm('Are you sure?');
if (result === true) {
var index = getSelectedIndex(del);
del.splice(index, 1);
};
};

function getSelectedIndex (del) {
console.log(del);
for(var i = 0; i < del.length; i++)
if(del[i].id == del)
return i;
return -1;
};

index.html

      <button class="btn btn-danger btn-sm ng-scope"  ng-click="Delete($storage.extraTodo)"><span class="glyphicon glyphicon-trash"></span></button>
<button class="btn btn-danger btn-sm ng-scope" ng-click="Delete($storage.todos)"><span class="glyphicon glyphicon-trash"></span></button>

最佳答案

假设您想根据 ID 从 todos 中删除一个对象,您可以创建一个以 ID 作为参数的函数,然后删除具有该 ID 的任何对象。使用您的命名并假设 todos 是您正在使用的任何内容:

$scope.Delete = function(id) {
todos = todos.filter(function(item) {
return item.id !== id;
});
}

关于javascript - 如何正确从表中删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34323025/

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