Javascript – How to use ng-repeat $index to find element in array

angularjsangularjs-ng-repeatarraysjavascript

In my $scope, I have a property that's an array of cars appropriately name $scope.cars. User has ability to delete a car. I pass the $index (created by ng-repeat) of the car as a parameter to delete function deleteThis, however in JavaScript function where I receive parameter $index, I do not know how to use the index created by ng-repeat to find the car to remove from $scope.cars, since $index is not native part of $scope.cars. Please tell me how

$scope.deleteThis = function($event, $index){
   // how can I use $index to find car in $scope.cars to delete

}

<div ng-repeat="car in cars">   
<div class="row">
<div class="col-md-1"><h2>{{car.name}}</h2>{{car.make}}</div>

<div class="col-md-2"></div>
<span class="delete" ng-click="deleteThis($event, $index)">x</span>
</div>

Best Answer

You do not need to use index, you can just pass the object car and splice it out.

<span class="delete" ng-click="deleteThis(car)">x</span>

and

$scope.deleteThis = function(car){
   var cars = $scope.cars;
   cars.splice(cars.indexOf(car), 1);
}

You can use $index as well (but using $index is tricky when you have filters like orderBy or any other filter combined with the ng-repeat expression, $index might not be the real index in the original array). $index is not attached to the repeated object but it is attached to the child scope created by ng-repeat. Passing car is more readable and explicit as opposed to using $index and more reusable if you were to reuse the partial view inside the ng-repeat.

If you were to still use index, then just do:

$scope.deleteThis = function(index){
    $scope.cars.splice(index, 1);
}