我正在尝试从数组$scope.items
中删除元素,以便在视图ng-repeat="item in items"
中删除项
出于演示的目的,下面是一些代码:
for(i=0;i<$scope.items.length;i++){
if($scope.items[i].name == 'ted'){
$scope.items.shift();
}
}
如果有名称ted,我想从视图中删除第一个元素,对吗?它工作得很好,但是视图会重新加载所有元素。因为所有的数组键都移位了。这在我正在创建的移动应用程序中造成了不必要的延迟。
有谁有解决这个问题的办法吗?
发布于 2014-03-04 08:42:40
对于任何回到这个问题的人。从数组中删除项的正确“角度方式”是使用$filter。只需将$filter注入您的控制器,然后执行以下操作:
$scope.items = $filter('filter')($scope.items, {name: '!ted'})
您不需要加载任何额外的库或求助于Javascript原语。
发布于 2014-02-24 02:42:44
你可以使用普通的javascript - Array.prototype.filter()
$scope.items = $scope.items.filter(function(item) {
return item.name !== 'ted';
});
发布于 2014-05-22 23:33:01
只是对“angular”解决方案进行了轻微的扩展。我想排除一个基于它的数字id的项目,所以!方法不起作用。适用于{ name:'ted‘}或{ id: 42 }的更通用的解决方案是:
mycollection = $filter('filter')(myCollection, { id: theId }, function (obj, test) {
return obj !== test; });
https://stackoverflow.com/questions/18303040
复制相似问题