I am trying to remove elements from the array $scope.items so that items are removed in the view ng-repeat="item in items"
Just for demonstrative purposes here is some code:
for(i=0;i<$scope.items.length;i++){
if($scope.items[i].name == 'ted'){
$scope.items.shift();
}
}
I want to remove the 1st element from the view if there is the name ted right? It works fine, but the view reloads all the elements. Because all the array keys have shifted. This is creating unnecessary lag in the mobile app I am creating..
Anyone have an solutions to this problem?
-
I've used splice successfully to modify an array that is used in ng-repeat with no weird side effects.BoxerBucks– BoxerBucks2013年08月18日 19:57:39 +00:00Commented Aug 18, 2013 at 19:57
-
Looks like the items is an array of array, or you can't call items[i].shift();zs2020– zs20202013年08月18日 20:12:03 +00:00Commented Aug 18, 2013 at 20:12
-
Hi, thanks for the replies. Sorry, there was a typos in the code of my question, i've just updated it.TheNickyYo– TheNickyYo2013年08月18日 20:21:25 +00:00Commented Aug 18, 2013 at 20:21
-
Then why you remove the first element from the array rather than the element at the position i?zs2020– zs20202013年08月18日 20:25:29 +00:00Commented Aug 18, 2013 at 20:25
-
3 rows will solve you the problem, just add $filter in controllerMaxim Shoustin– Maxim Shoustin2013年08月18日 21:25:03 +00:00Commented Aug 18, 2013 at 21:25
12 Answers 12
There is no rocket science in deleting items from array. To delete items from any array you need to use splice: $scope.items.splice(index, 1);. Here is an example:
HTML
<!DOCTYPE html>
<html data-ng-app="demo">
<head>
<script data-require="[email protected]" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div data-ng-controller="DemoController">
<ul>
<li data-ng-repeat="item in items">
{{item}}
<button data-ng-click="removeItem($index)">Remove</button>
</li>
</ul>
<input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>
</div>
</body>
</html>
JavaScript
"use strict";
var demo = angular.module("demo", []);
function DemoController($scope){
$scope.items = [
"potatoes",
"tomatoes",
"flour",
"sugar",
"salt"
];
$scope.addItem = function(item){
$scope.items.push(item);
$scope.newItem = null;
}
$scope.removeItem = function(index){
$scope.items.splice(index, 1);
}
}
6 Comments
$index does not necessarily match $scope.items indexes. Especially if you use orderBy or filter. I think using $index is not scalable and may be dangerous.For anyone returning to this question. The correct "Angular Way" to remove items from an array is with $filter. Just inject $filter into your controller and do the following:
$scope.items = $filter('filter')($scope.items, {name: '!ted'})
You don't need to load any additional libraries or resort to Javascript primitives.
6 Comments
$filter('filter')($scope.items, {name: '!ted'}, true) , see docs.angularjs.org/api/ng/filter/filter $filter('filter')($scope.items, {id: 42}, true); works for finding the element, but I haven't found a way to negate it, {id: "!42"} doesn't work since it's a string instead.$filter('filter')($scope.items, function(value, index) {return value.id !== 42;});You can use plain javascript - Array.prototype.filter()
$scope.items = $scope.items.filter(function(item) {
return item.name !== 'ted';
});
Comments
Because when you do shift() on an array, it changes the length of the array. So the for loop will be messed up. You can loop through from end to front to avoid this problem.
Btw, I assume you try to remove the element at the position i rather than the first element of the array. ($scope.items.shift(); in your code will remove the first element of the array)
for(var i = $scope.items.length - 1; i >= 0; i--){
if($scope.items[i].name == 'ted'){
$scope.items.splice(i,1);
}
}
Comments
Here is filter with Underscore library might help you, we remove item with name "ted"
$scope.items = _.filter($scope.items, function(item) {
return !(item.name == 'ted');
});
4 Comments
$scope.items = $filter('filter').filter($scope.items, {name: '!ted'}) $scope.items = $filter('filter')($scope.items, {name: '!ted'})I liked the solution provided by @madhead
However the problem I had is that it wouldn't work for a sorted list so instead of passing the index to the delete function I passed the item and then got the index via indexof
e.g.:
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
An updated version of madheads example is below: link to example
HTML
<!DOCTYPE html>
<html data-ng-app="demo">
<head>
<script data-require="[email protected]" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div data-ng-controller="DemoController">
<ul>
<li data-ng-repeat="item in items|orderBy:'toString()'">
{{item}}
<button data-ng-click="removeItem(item)">Remove</button>
</li>
</ul>
<input data-ng-model="newItem"><button data-ng-click="addItem(newItem)">Add</button>
</div>
</body>
</html>
JavaScript
"use strict";
var demo = angular.module("demo", []);
function DemoController($scope){
$scope.items = [
"potatoes",
"tomatoes",
"flour",
"sugar",
"salt"
];
$scope.addItem = function(item){
$scope.items.push(item);
$scope.newItem = null;
}
$scope.removeItem = function(item){
var index = $scope.items.indexOf(item);
$scope.items.splice(index, 1);
}
}
Comments
Just a slight expansion on the 'angular' solution. I wanted to exclude an item based on it's numeric id, so the ! approach doesn't work. The more general solution which should work for { name: 'ted' } or { id: 42 } is:
mycollection = $filter('filter')(myCollection, { id: theId }, function (obj, test) {
return obj !== test; });
Comments
My solution to this (which hasn't caused any performance issues):
- Extend the array object with a method remove (i'm sure you will need it more than just one time):
Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); };
I'm using it in all of my projects and credits go to John Resig John Resig's Site
- Using forEach and a basic check:
$scope.items.forEach(function(element, index, array){ if(element.name === 'ted'){ $scope.items.remove(index); } });
At the end the $digest will be fired in angularjs and my UI is updated immediately without any recognizable lag.
4 Comments
index will still reflect the index from the original array but the index of the same item in the current $scope.items will be one value less for each of the preceeding items that were removed. So while it is safe to remove items while iterating using forEach, it is NOT SAFE to use the index provided in the callback to do so.If you have any function associated to list ,when you make the splice function, the association is deleted too. My solution:
$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) ] });
});
};
The list param is named items. The param x.done indicate if the item will be deleted. Hope help you. Greetings.
Comments
Using the indexOf function was not cutting it on my collection of REST resources.
I had to create a function that retrieves the array index of a resource sitting in a collection of resources:
factory.getResourceIndex = function(resources, resource) {
var index = -1;
for (var i = 0; i < resources.length; i++) {
if (resources[i].id == resource.id) {
index = i;
}
}
return index;
}
$scope.unassignedTeams.splice(CommonService.getResourceIndex($scope.unassignedTeams, data), 1);
Comments
My solution was quite straight forward
app.controller('TaskController', function($scope) {
$scope.items = tasks;
$scope.addTask = function(task) {
task.created = Date.now();
$scope.items.push(task);
console.log($scope.items);
};
$scope.removeItem = function(item) {
// item is the index value which is obtained using $index in ng-repeat
$scope.items.splice(item, 1);
}
});
Comments
My items have unique id's. I am deleting one by filtering the model with angulars $filter service:
var myModel = [{id:12345, ...},{},{},...,{}];
...
// working within the item
function doSthWithItem(item){
...
myModel = $filter('filter')(myModel, function(value, index)
{return value.id !== item.id;}
);
}
As id you could also use the $$hashKey property of your model items: $$hashKey:"object:91"
Comments
Explore related questions
See similar questions with these tags.