How to filter the data in angularjs?

2019-08-28 10:27发布

问题:

I am trying to filter the data according to firstname and title properties but it's not filtering.

<label>by Name 
  <input type="text" ng-model="searchText.data.firstname"></label> |

<label>by Title
  <select name="title">
    <option value="">All</option>
    <option value="">Zone Manager</option>
    <option value="">Logistic agent</option>
  </select></label>

<hr/>

<div ng-repeat="accDetails in acct_list | filter:searchText">
   {{accDetails.data.firstname}} |
   {{accDetails.data.lastname}} | 
   {{accDetails.title}}

</div>

The JSON data is:

$scope.acct_list = {
  "0": {
    "data": {
        "firstname": "maeli",
        "lastname": "mad",
        //...
    },
    "title": "Shop"
  },
  "1": {
    "data": {
        //...
    },
    "title": "hotel"
  }
}

Here is my plnkr

回答1:

The reason that filtering doesn't work is because filter only works on arrays, and your acct_list is not an array.

You can either change your data to an array:

$scope.acct_list = [
  {
    "data": {
        "firstname": "maeli",
        "lastname": "mad",
        //...
    },
    "title": "Shop"
  },
  {
    ...
  }
]

or, arrange into an array in the controller and ng-repeat over that.

Here's another relevant SO question on this topic.

Also, don't forget to add ng-model="searchText.title" to your <select> and fill-in the <option> values accordingly.