AngularJS过滤器(函数和输入搜索一起)



我想通过使用AngularJS同时使用过滤器函数和输入搜索。我可以使用多种功能。但是在添加用于搜索的文本框时,我遇到了一些错误。有什么办法可以做到这一点吗?我尝试了一些方法,但没有人不起作用。

提前谢谢。

示例代码如下

var app = angular.module("app", []),
  url = "http://www.filltext.com/?rows=50&pretty=true&fName={firstName}&age=[18,19,20,21]";
app.controller("controller", function($scope, $http) {
  $http.get(url)
    .success(function(resp) {
      $scope.list = resp;
    });
  $scope.filterAge = function(item) {
    return item.age > 19;
  };
});
<!DOCTYPE html>
<html ng-app="app">
<head>
  <script src="https://code.jquery.com/jquery.min.js"></script>
  <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  <meta charset="utf-8">
  <title>AngularJS Filter</title>
</head>
<body ng-controller="controller">
  <div class="container">
    <br>
    <input type="text" ng-model="search" placeholder="Search..." />
    <table class="table table-striped">
      <thead>
        <th>Name</th>
        <th>Age</th>
      </thead>
      <tbody>
        <tr ng-repeat="item in list | filter: filterAge">
          <td>{{ item.fName }}</td>
          <td>{{ item.age }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</body>
</html>

您应该将自定义过滤器添加到角度模块,而不是向控制器添加过滤器功能。这是一个例子:

自定义过滤器:

.filter('filterByAge', function filterByAge() {
  return function(array, age) {
    var filteredArray = [];
    angular.forEach(array, function(item) {
      if (item.age > age) {
        filteredArray.push(item);
      }
    });
    return filteredArray;
  }
});

.HTML

<input type="text" ng-model="search" placeholder="Search..." />
<table class="table table-striped">
  <thead>
    <th>Name</th>
    <th>Age</th>
  </thead>
  <tbody>
    <tr ng-repeat="item in list | filter: search | filterByAge:19">
      <td>{{ item.fName }}</td>
      <td>{{ item.age }}</td>
    </tr>
  </tbody>
</table>
 $scope.$watch('search', function (data) {
    //sorting logic
})

观察程序正在等待对提交的搜索执行的任何操作,然后执行函数。

最新更新