使用过滤器后获取元素的索引 [英] Get element's index after using filter

查看:31
本文介绍了使用过滤器后获取元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含对象的数组.我想找到特定对象的索引.这个对象有一个唯一的 id 属性值,我可以用 $filter 找到它:

I have an array with objects. I want to find a specific object's index. This object has an unique id property' value , and i can find it with a $filter :

 var el = $filter('filter')( tabs, { id: id })[0]; // "el" is my unique element 

但是我怎么知道这个元素在它的原始数组中的索引是什么?$filter 可以提供我这个信息吗?

But how can i know what is the index of this element in it's original array? Does $filter can provide me this information?

到目前为止我还没有找到 Angular 解决方案,因为我在 这个页面上找不到太多有用的信息.所以我使用了 ArrayindexOf 方法:

By now i didn't find an Angular solution, because i can't get much useful info on this page. So i have used Array's indexOf method :

 var el_index = tabs.indexOf( el );

http://jsfiddle.net/BhxVV/

要获取具有特定 id 的所有元素的索引,我们采用类似的方法:

To get indexes of all elements with specific id we go the similar way:

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

http://jsfiddle.net/BnBCS/1/

但是它太长了,我确定我在这里重新发明轮子...

But it is too long and i'm sure that i'm reinventing the wheel here...

推荐答案

试试这个选项:

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

我认为它有点简短明了.

I think it a bit short and clear.

小提琴

这篇关于使用过滤器后获取元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆