适用limitTo只对某些项目组 [英] Apply limitTo only to certain group of items

查看:159
本文介绍了适用limitTo只对某些项目组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$scope.items = [
    {"name":"laptop","color":"green"},
    {"name":"shoe","color":"blue"},
    {"name":"Car","color":"gold"},
    {"name":"Car","color":"gold"},
    {"name":"Car","color":"gold"}
];

我怎么能限制包含名称='车',以2项但保持其他项目中不受影响 NG-重复?如果我做<李NG重复=中的项项|过滤器:{名称:'车'} | limitTo:2> ,它将返回2辆车结果,但随后的其他项目都没有了。

How can I limit the items that contain name = 'car' to 2 yet keep other items unaffected in ng-repeat? If I do <li ng-repeat="item in items | filter: {name: 'car'} | limitTo: 2">, it will return 2 car results, but then the other items are gone.

推荐答案

您的场景听起来更像是更多地涉及商业逻辑不是一个功能框架应包括的东西。尝试实现自己的自定义过滤器。

Your scenario sounds more like something related more to a "business logic" than a feature a framework should incorporate. Try implementing your own custom filter.

接近的东西:

自定义过滤器

angular.module('myApp', []).filter('myFilter', function() {
  return function(items, param1, param2) {
    return items.reduce(function(a,c){  var count = a.filter(function(item){ return item.name ===param1; }).length; if(count<param2 || c.name !== param1 ) a.push(c); return a;},[]);
  };
});

和在 HTML

 <li ng-repeat="item in items | myFilter:'car': 2">

当然,你可以扩展和执行更适合您的应用程序需要的操作。

Of course you could extend and perform the actions that are more suited to your app needs.

下面是 plunker演示

这篇关于适用limitTo只对某些项目组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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