Angular 自定义搜索过滤器

Angular custom search filter

我需要为此范围创建自定义搜索过滤器。我尝试了默认的过滤功能,但没有用,因为我在 HTML 中将状态显示为字符串,但没有按照我想要的方式进行过滤。如果我在文本框中键入 Normal,则不会发生任何事情,因为数据是 0、1 和 2。如果我搜索 2016/05/16 格式的购买时间,也无法搜索。

$scope.orderHistory = {[
    "purchaseTime": 1437536718345,
    "status": 1,
]};
app.filter('filterSearch', function () {
  //what to do here??
});


<input type="text" ng-model="searchReview">

<div dir-paginate="order in orderHistory|filterSearch:searchReview">
<ul>
 <li><p class="table-data2-h">{{ order.purchaseTime | date : 'yyyy/MM/dd'}} </p></li>
<li>
<span ng-if="order.status == 0 ">Stable</span>
<span ng-if="order.status == 1 ">Normal</span>
<span ng-if="order.status == 2 ">Serious</span>
</li>
</div>

起初,我看到你的code有些错误,你可以在下面进行比较。

我建议你创建一个简单的 function 来根据你的要求解析你的属性,仅在 initilization 时(肯定会更好地每次解析当 custom filter 被调用时),那么你可以使用 normal filter.

看到它工作:

(function() {
  'use strict';

  angular
    .module('app', [])
    .constant('STATUS', {
      0: 'Stable',
      1: 'Normal',
      2: 'Serious'
    })
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope', 'STATUS'];

  function MainCtrl($scope, STATUS) {
    $scope.orderHistory = [
      {
        "purchaseTime": 1437536718345,
        "status": 1
      },
      {
        "purchaseTime": 1431236718345,
        "status": 0
      },
      {
        "purchaseTime": 1099536718345,
        "status": 2
      },
      {
        "purchaseTime": 1439744718345,
        "status": 1
      }
    ];

    function parseProperties() {
      $scope.orderHistory.map(function(order) {
        // You can do it with switch statement
        // switch (order.status) {
        //   case 0:
        //     order.status = 'Stable';
        //     break;
        //   case 1:
        //     order.status = 'Normal';
        //     break;
        //   case 2:
        //     order.status = 'Serious';
        //     break;
        // }

        // or using a constant that you can define above
        order.status = STATUS[order.status];

        order.purchaseTime = new Date(order.purchaseTime).toLocaleDateString();
        return order;
      });
    }

    parseProperties();
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input type="text" placeholder="Search..." ng-model="searchReview">
  <div ng-repeat="order in orderHistory | filter: searchReview">
    <ul>
      <li>
        <p class="table-data2-h" ng-bind="order.purchaseTime"></p>
      </li>
      <li ng-bind="order.status"></li>
    </ul>
  </div>
</body>

</html>

希望对你有帮助