be-codified be-codified - 2 years ago 86
AngularJS Question

How to remove object from array within ng-repeat with AngularJS?

I am having an array with objects like [{...}, {...}] which I am outputting with ng-repeat. Then I have a delete button with a function to delete it.

Is there a simple way to delete it in AngularJS, perhaps with $index? Or I need to specify an ID on every object as an property?

Answer Source

If you don't apply a filter to reorder or filter your array, you can do this:

<div ng-repeat="item in items" ng-click="delete($index)">{{item}}</div>

And the delete function:

$scope.items = [...];

$scope.delete = function (index) {
    $scope.items.splice(index, 1);

Another way to do it without filter problems: (ONLY IE9+)

<div ng-repeat="item in items | orderBy: 'id'" ng-click="delete(item)">{{item}}</div>

And the delete function:

$scope.items = [...];

$scope.delete = function (item) {
    $scope.items.splice($scope.items.indexOf(item), 1);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download