ng-repeat filter to iterate only over elements wit

2019-06-01 05:37发布

I want to ng-repeat through an array, but filter the results so that only the elements that match a certain property value will be displayed. Is this possible, and how?

Here's an example of what I'm trying to do (and obviously failing):

HTML (View)

<ul>
  <li ng-repeat="person in people | filter: person.gender == 'male'"></li>
</ul>

<ul>
  <li ng-repeat="person in people | filter: person.gender == 'female'"></li>
</ul>

JS (Controller)

$scope.people = [

  {name: "John", gender: "male"},

  {name: "Sue", gender: "female"},

  {name: "Maria", gender: "female"},

  {name: "Bob", gender: "male"},

]

So the first list should just print the male names, and the second female, based on the property values.

Is this possible using ng-repeat's filter? Or if not is there another way?

Thanks in advance

1条回答
女痞
2楼-- · 2019-06-01 06:06

try this. if put :true after filter then filtering do exactly on match value.

function Main($scope) {
    $scope.people = [

  {name: "John", gender: "male"},

  {name: "Sue", gender: "female"},

  {name: "Maria", gender: "female"},

  {name: "Bob", gender: "male"}

];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
    <div ng-controller="Main">
      <ul>
  <li ng-repeat="person in people | filter: { gender: 'male' }:true">
   {{person.name}}
  </li>
</ul>

    </div>
</div>

查看更多
登录 后发表回答