我有一个包含对象的数组。我想找到特定对象的索引。这个对象有一个唯一的 id
属性值,我可以用 $filter
找到它:
var el = $filter('filter')( tabs, { id: id })[0]; // "el" is my unique element
但是我怎么知道这个元素在它的原始数组中的索引是什么? $filter
可以向我提供此信息吗?
到目前为止,我还没有找到 Angular 解决方案,因为我无法在 this page 上获得很多有用的信息。 .所以我使用了 Array
的 indexOf
方法:
var el_index = tabs.indexOf( el );
要获取具有特定 id
的所有元素的索引,我们采用类似的方式:
$scope.getTabsIndexes = function(id){
var els = $filter('filter')( tabs , { id: id });
var indexes = [];
if(els.length) {
var last_i=0;
while( els.length ){
indexes.push( last_i = tabs.indexOf( els.shift() , last_i ) );
}
}
return indexes;
}
但它太长了,我确定我正在重新发明轮子...
最佳答案
试试这个选项:
$scope.search = function(selectedItem) {
$filter('filter')($scope.tabs, function(item) {
if(selectedItem == item.id){
$scope.indexes.push( $scope.tabs.indexOf(item) );
return true;
}
return false;
});
}
我觉得它有点简短明了。
参见 Fiddle
关于javascript - 使用过滤器后获取元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19050747/