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 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.:
An updated version of madheads example is below: link to example
HTML
JavaScript
My items have unique id's. I am deleting one by filtering the model with angulars
$filter
service:As id you could also use the $$hashKey property of your model items:
$$hashKey:"object:91"
My solution to this (which hasn't caused any performance issues):
I'm using it in all of my projects and credits go to John Resig John Resig's Site
At the end the $digest will be fired in angularjs and my UI is updated immediately without any recognizable lag.
My solution was quite straight forward
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
JavaScript
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)