Question

Say I have

<div ng-repeat="item in scope.allItems">
   <div ng-click="doSomething(...)"></div>
</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
}
Was it helpful?

Solution

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);
};

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top