如何在Angularjs中创建过滤器

如何在Angularjs中创建过滤器

本文介绍了如何在Angularjs中创建过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个课程集:

  [{id:1,courseId:2,text:'John'} ,
{id:2,courseId:2,text:'Willi'},
{id:3,courseId:2,text:'Inga'},
{id: courseId:1,text:'Jerry'},
{id:5,courseId:1,text:'Michael'},
{id:1,courseId:3,text:'John'} ,
{id:2,courseId:3,text:'Willi'},
{id:3,courseId:4,text:'Inga'},
{id: courseId:5,text:'Jerry'},
{id:5,courseId:5,text:'Michael'}]

我有这个id数组:

  [{id:3} ,{id:2},{id:1}] 

我需要过滤数组数组的数组(即仅显示课程id = 3,2,1的文本课程):

  ng -repeat =课程课程| customFilter:[{id:3},{id:2},{id:1}]

我需要创建自定义f任何想法如何为此目的实现customFilter?


$ b class =h2_lin>解决方案

您可以创建您的自定义过滤器,以便为您提供过滤的值,过滤器应将数组的元素



标记

   

过滤器

  app.filter('customFilter',function ){
return function(array,filterArray){
var ids = [];
angular.forEach(filterArray,function(val,index){
ids.push 。$)
}
return array.filter(function(value){
return ids.indexOf(value.id)!== -1;
});
}
})


I have this collection of courses:

 [{ id: 1, courseId: 2, text: 'John' },
  { id: 2, courseId: 2, text: 'Willi' },
  { id: 3, courseId: 2, text: 'Inga' },
  { id: 4, courseId: 1, text: 'Jerry' },
  { id: 5, courseId: 1, text: 'Michael' },
  { id: 1, courseId: 3, text: 'John' },
  { id: 2, courseId: 3, text: 'Willi' },
  { id: 3, courseId: 4, text: 'Inga' },
  { id: 4, courseId: 5, text: 'Jerry' },
  { id: 5, courseId: 5, text: 'Michael' }]

And I have this array of id's:

[{"id": 3},{"id": 2},{"id": 1}]

I need to filter array of courses by array of id's(i.e to display only text courses that have courseId = 3,2,1 ):

ng-repeat="course in courses| customFilter: [{"id": 3},{"id": 2},{"id": 1}]"

I need to create custom filter in angularJS that will filter array of courses by array of id's.

Any idea how can I implement customFilter for this purpose?

解决方案

You could create your custom filter so that can provide you the filtered values, filter should take array of element to be filter array.

Markup

ng-repeat="course in courses| customFilter: [{"id": 3},{"id": 2},{"id": 1}]""

Filter

app.filter('customFilter', function(){
  return function(array, filterArray){
     var ids = [];
     angular.forEach(filterArray, function(val, index) {
        ids.push(val.id);
     }
     return array.filter(function(value){
        return ids.indexOf(value.id) !== -1;
     });
  }
})

这篇关于如何在Angularjs中创建过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 14:10