Question

When I filter ng-repeat, this.$index and key both change to reflect the objects position in the filtered array.

The problem is that I only see the unfiltered array from the JavaScript so this.$index and key are giving an unexpected result.

HTML:

<section ng-repeat="( key, place ) in places | filter: ({ name : placeName })" >

<button ng-click='myFunc( this.$index )'>Pick {{place.name}}</button> <!-- same issue with key -->
<section>

Javascript:

myFunc(key){
console.log( $scope.places[key] ); 
} 

I can loop over the array and find $id or my own identifier but that seems wasteful when all I need is an index that I can pass on to my function which is looking at the unfiltered array.

Thanks.

Was it helpful?

Solution

Instead of passing in the index, pass in the actual object:

<section ng-repeat="( key, place ) in places | filter: ({ name : placeName })" >

<button ng-click='myFunc( place )'>Pick {{place.name}}</button> 
<!-- same issue with key -->
<section>

Then in your JavaScript

$scope.myFunc(place){
    console.log( place ); 
}

This will make testing the myFunc method even easier since you are supplying the object in which you will be acting upon.

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