Filtering a table by column with ng-repeat

2019-08-09 04:55发布

问题:

I'm building an application using Angular.js. In this app I'm getting some data via AJAX in JSON format. I'm showing this data listed in a table, and I put a search text input to filter it.

I implemented the filter this way:

[...]
<input ng-model="searchText"/>
[...]
<tr ng-repeat="data in datarray | filter:searchText">
<td>{{data.title}}<td>
<td>{{data.message}}<td>
<tr>
[...]

What I want (and don't know how) to do is filtering this data only for certain fields (e.g. its title).

For example: if I have data[0] with title "cats" and message "cats and dogs", and data[1] titled "dogs" and with message "cats and dogs", and I search for "cats", I want only data[0] to be shown, without considering data messages but only the titles.

回答1:

As provided in the doc : https://docs.angularjs.org/api/ng/filter/filter

you should set your ng-model correctly :

<input ng-model="search.title" />

you can also combine search columns :

<input ng-model="search.title" />
<input ng-model="search.message" />

and in your filter :

<tr ng-repeat="data in datarray | filter:search">
  <td>{{data.title}}<td>
  <td>{{data.message}}<td>
<tr>

Here is a demo : http://plnkr.co/edit/LCWV35PvbU7rLQvgqiOw?p=preview



回答2:

i am modifying same code of @igloob this is work for filter all/any columns...

<!DOCTYPE html>
<html ng-app="filterExample">

<head>
<script data-require="angular.js@1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body ng-controller="FilterController as filterCtrl">    

<input ng-model="search" />
<table>
  <tbody>
    <tr ng-repeat="item in filterCtrl.data | filter:search">
      <td>{{item.title}}</td>
      <td>{{item.message}}</td>
    </tr>
  </tbody>
</table>

<script>
  var filterModule = angular.module ("filterExample", []);

  filterModule.controller ("FilterController", function () {
  this.data = [{title:"abc", message:"def"}, {title:"aef", message:"jkl"},
  {title:"efg", message:"asc"}];

});
</script>
</body>

</html>