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?
Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.
To remove an object from a TypeScript array:Use the findIndex() method to get the index of the object. Use the splice() method to remove the object from the array. The splice method will remove the object from the array and will return the removed object.
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); } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With