我在我的控制器中创建了一个删除功能,但它没有正常工作。它总是删除数组表中的最后一个对象。可能是什么问题?
谢谢!
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>
答案 0 :(得分:1)
假设您要根据其ID从todos
删除对象,您可以创建一个以ID作为参数的函数,然后删除具有该ID的任何对象。使用您的命名并假设todos
是您正在使用的任何内容:
$scope.Delete = function(id) {
todos = todos.filter(function(item) {
return item.id !== id;
});
}
答案 1 :(得分:0)
它将从$ scope。$ storage中删除对象(例如:del)。
$scope.Delete = function (del) {
var result = confirm('Are you sure?');
if (result === true) {
var index = $scope.$storage.indexOf(del);
$scope.$storage.splice(index, 1);
};
};