[英]How to remove the element with respect to array key?
我有一个如下的javascript数组:
$scope.products = [
{id:'1', name:'IPhone6', price: '1,000 AED', quantity: '2'},
{id:'2', name:'Samsung Mini', price: '750 AED', quantity: '1'},
{id:'3', name:'Dell Laptop', price: '1700 AED', quantity: '3'},
{id:'4', name:'HCL Monitor 7"', price: '650 AED', quantity: '7'},
];
使用ng-repeat
Angular js函数显示以上数组。
我正在调用remove函数并将id
作为参数传递。 如何从数组中删除特定元素?
$scope.products.slice($id, 1)
。 我必须删除ID吗? 请指教。
这应该工作:
// id = '3'
$scope.products = $scope.products.filter(function (p) { return p.id !== id });
检出拼接方法
您可能希望将具有您提供的id的元素的索引传递给remove函数,这样做可以描述getIndexBy函数
Array.prototype.getIndexBy = function (name, value) {
for (var i = 0; i < this.length; i++) {
if (this[i][name] == value) {
return i;
}
}
}
并像这样使用
index=products.getIndexBy("id", 3)
其中3是您提供的ID。 然后,您可以在splice方法中使用此索引来删除特定元素。
假设您要按索引删除一个元素。
您可以定义一个实用函数 :
(function(window) {
var utility = window.utility|| (window.utility= {});
function remove(items, fn) {
var toRemove = [];
angular.forEach(items, function(item, i) {
if (fn(item)) {
toRemove.push(i);
}
});
angular.forEach(toRemove, function(index) {
items.splice(index,1);
});
}
angular.extend(utility, {
'remove': remove
});
})(window);
要使用此函数,请将项目数组作为第一个参数,将谓词函数作为第二个参数。 谓词返回true的所有项目将从数组中删除该项目:
例子:
删除所有名称为“ john”的用户:
utility.remove($scope.users, function(user) {
return user.name == 'john';
});
要删除ID为3的用户:
utility.remove($scope.users, function(user) {
return user.id == 3;
});
在这样的点击操作中使用$ index
ng-click='slice($index);'
和你这样的功能
$scope.slice = function(element){
$scope.friends.splice(element, 1);
}
或通过以下示例:
HTML代码
<ul>
<li ng-repeat="product in products" ng-click='slice($index);'>
[{{$index + 1}}] {{product.name}}
</li>
</ul>
JavaScript代码
$scope.products = [
{id:'1', name:'IPhone6', price: '1,000 AED', quantity: '2'},
{id:'2', name:'Samsung Mini', price: '750 AED', quantity: '1'},
{id:'3', name:'Dell Laptop', price: '1700 AED', quantity: '3'},
{id:'4', name:'HCL Monitor 7"', price: '650 AED', quantity: '7'},
];
$scope.slice = function(element){
$scope.friends.splice(element, 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.