AngularJS - Pass $index or the item itself via ng-click?


Say I have

<div ng-repeat="item in scope.allItems">
   <div ng-click="doSomething(...)"></div>

If I want to do something with item upon click, which one is a better option?

Option 1

Use ng-click="doSomething($index) and have:

$scope.doSomething = function($index) {
    var myItem = $scope.allItems[$index];

Option 2

Use ng-click="doSomething(item) and have:

$scope.doSomething = function(myItem) {
    // Do whatever
Problem courtesy of: Kousha


If you are just doing something to the item, pass that in. This way the function doesn't need to know which array the item belongs to:

$scope.addColor = function(car) {
  car.color = 'red';

If, on the other hand, you need to modify the array I prefer to pass in $index and save having to loop through the array looking for a match:

$scope.deleteCar = function(index, cars) {
  cars.splice(index, 1);
Solution courtesy of: j.wittwer


If you want use filter for scope.allItems, use Option 2 - because using filters change element $index. If you don't use filter,you can use Option 1. IMHO Option 2 more easy and useful than Option 1, so i already use Option 2.

Discussion courtesy of: strelok2010

This recipe can be found in it's original form on Stack Over Flow.