简单的待办事项清单,但每个项目的清单页面上都有一个删除按钮:
相关模板HTML:
<tr ng-repeat="person in persons">
<td>{{person.name}} - # {{person.id}}</td>
<td>{{person.description}}</td>
<td nowrap=nowrap>
<a href="#!/edit"><i class="icon-edit"></i></a>
<button ng-click="delete(person)"><i class="icon-minus-sign"></i></button>
</td>
</tr>
相关控制器方法:
$scope.delete = function (person) {
API.DeletePerson({ id: person.id }, function (success) {
// I need some code here to pull the person from my scope.
});
};
我试着$scope.persons.pull(person)
和$scope.persons.remove(person)
。
尽管数据库已成功删除,但是我无法从范围中拉出该项目,并且我不想对服务器进行方法调用以获取客户端已经拥有的数据,我只想从范围中删除此人。
有任何想法吗?
您的问题不是Angular,而是Array方法。从数组中删除特定项目的正确方法是使用Array.splice
。另外,使用ng-repeat时,您可以访问特殊$index
属性,该属性是您传入的数组的当前索引。
该解决方案实际上非常简单:
视图:
<a ng-click="delete($index)">Delete</a>
控制器:
$scope.delete = function ( idx ) {
var person_to_delete = $scope.persons[idx];
API.DeletePerson({ id: person_to_delete.id }, function (success) {
$scope.persons.splice(idx, 1);
});
};
您必须person
在persons
数组中找到的索引,然后使用数组的splice
方法:
$scope.persons.splice( $scope.persons.indexOf(person), 1 );
我将使用Underscore.js库,其中包含有用的功能列表。
without
without_.without(array, *values)
返回已删除值的所有实例的数组的副本。
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
例
var res = "deleteMe";
$scope.nodes = [
{
name: "Node-1-1"
},
{
name: "Node-1-2"
},
{
name: "deleteMe"
}
];
$scope.newNodes = _.without($scope.nodes, _.findWhere($scope.nodes, {
name: res
}));
参见JSFiddle中的Demo 。
filter
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
// => [2, 4, 6]
例
$scope.newNodes = _.filter($scope.nodes, function(node) {
return !(node.name == res);
});
参见小提琴中的演示。
$scope.removeItem = function() {
$scope.items.splice($scope.toRemove, 1);
$scope.toRemove = null;
};
这对我有用!
如果您有与list相关联的任何功能,则在执行拼接功能时,该关联也将被删除。我的解决方案:
$scope.remove = function() {
var oldList = $scope.items;
$scope.items = [];
angular.forEach(oldList, function(x) {
if (! x.done) $scope.items.push( { [ DATA OF EACH ITEM USING oldList(x) ] });
});
};
列表参数被命名为items。参数x.done指示是否将删除该项目。
另一个参考:另一个例子
希望对你有帮助。问候。
对于@Joseph Silber的可接受答案无效,因为indexOf返回-1。这可能是因为Angular添加了一个hashkey,这对于我的$ scope.items [0]和我的商品而言是不同的。我试图用angular.toJson()函数解决此问题,但是它没有用:(
啊,我找到了原因...我使用块方法通过查看$ scope.items在表中创建两列。抱歉!
你也可以用这个
$scope.persons = $filter('filter')($scope.persons , { id: ('!' + person.id) });
Angular有一个称为的内置函数arrayRemove
,在您的情况下,方法可以简单地是:
arrayRemove($scope.persons, person)
array.splice(array.pop(item));
要从范围中删除元素,请使用:
// remove an item
$scope.remove = function(index) {
$scope.items.splice(index, 1);
};
文章标签:angularjs , html , javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!