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

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

问题描述

我有对象的数组。我想找到一个特定对象的索引。这个对象有一个唯一的 ID 财产的价值,我可以用 $过滤器找到它:

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 

但我怎么能知道这是什么元素的索引在它的原始的数组?是否 $过滤器能给我提供这些信息?

到现在为止,我没有找到一个角度的解决方案,因为我无法得到的此页面。所以,我已经使用阵列的indexOf 方法:

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.

请参阅<大骨节病> 小提琴

See Fiddle

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

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