当我过滤ng-repeat时,此。$ index和键都会更改以反映过滤后数组中的对象位置。
问题是我只看到JavaScript中未过滤的数组,所以这个。$ index和key给出了意想不到的结果。
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] );
}
我可以循环遍历数组并查找$ id或我自己的标识符,但是当我需要的是一个索引时,我可以将其传递给我的函数,该函数正在查看未过滤的数组。
感谢。
答案 0 :(得分:2)
不是传入索引,而是传入实际对象:
<section ng-repeat="( key, place ) in places | filter: ({ name : placeName })" >
<button ng-click='myFunc( place )'>Pick {{place.name}}</button>
<!-- same issue with key -->
<section>
然后在你的JavaScript中
$scope.myFunc(place){
console.log( place );
}
这将使得测试myFunc方法变得更加容易,因为您提供了将要对其进行操作的对象。