从字符串的开头过滤ng-repeat元素

时间:2013-11-24 19:02:19

标签: angularjs filter

我正在尝试AngularJS,这是我的第一次尝试。我试图使用“开头”而不是“包含”之类的东西来过滤对象数组,但我不明白该怎么做。

假设我有一个像这样的elements数组

[{
  amount: 50
}, {
  amount: 25
}]

如果我想按5进行过滤,则会显示两条记录,而我只想显示第一条记录,即以5开头的记录。

这是我到目前为止所做的,对于循环部分(我还添加了排序和分页部分,即使可能没有影响我想要实现的目标)

<tr ng-repeat="element in elements | filter:search:strict | orderBy:predicate:reverse | filter:startFrom:currentPage*pageSize | limitTo:pageSize">
  <td>{{element.name}}</td>
  <td>{{hotel.amount}}</td>
</tr>

以及我写“5

的输入
<input class="pull-right" ng-model="search.amount">

我不了解如何在这里创建自定义处理程序,以便我可以解析每个第n项并查看它是否以传递的数字开头。

2 个答案:

答案 0 :(得分:4)

我只想编写基本的自定义过滤器:

<强> JS

var iApp = angular.module("App", []);

 iApp.filter('myfilter', function() {

   function strStartsWith(str, prefix) {
    return (str+"").indexOf(prefix) === 0;
   }


   return function( items, amount) {


    var filtered = [];

    angular.forEach(items, function(item) {
      if(strStartsWith(item.amount, amount)){
        filtered.push(item);
      }
    });

    return filtered;
  };
});

    iApp.controller('TestController', function($scope)
    {   
       $scope.amount='';

       $scope.elements = [
         { amount: 50},
         { amount: 25 }];                
     }); 

<强> HTML

<body data-ng-controller="TestController">

  <input class="pull-right" ng-model="amount">

        <table id="hotels">
            <tr data-ng-repeat="element in elements | myfilter:amount">
                <td>{{element.amount}}</td>
            </tr>
        </table>
        <br/>

    </body>

演示 Plunker

答案 1 :(得分:4)

Maxim的答案对我有所帮助,但我认为我会使用更为通用的解决方案来过滤平面列表或要在特定属性上过滤的对象列表。

<强> View Plunkr

/**
 * Filter a list for elements with start with the given string.
 * 
 * @param {Array} items - The list of items to filter
 * @param {String} prefix - The prefix to search for
 * @param {String} [itemProperty] - An optional property to use for the search
 *                                  if filtering a list of objects.
 */
.filter('startsWith', function() {
  return function(items, prefix, itemProperty) {
    return items.filter(function(item) {
      var findIn = itemProperty ? item[itemProperty] : item;
      return findIn.toString().indexOf(prefix) === 0;
    });
  };
})

使用示例

// item in flatList | startswith:<term>
var flatList = ['foo', 'bar', 'zulu']

// item in objectList | startswith:<term>:<key>
var objectList = [
  {value: 'foo', label: '-FOO-'},
  {value: 'bar', label: '-BAR-'}
];

要区分大小写,只需将.toLowerCase()应用于前缀和findIn