简体   繁体   中英

Angular ng-repeat conditional wrap items in element (filter items in ng-repeat group)

I'm trying to hide occupation name when filtered user is not found in some occupation.

JS:

$scope.contacts = [
    {name: 'John', occupation: 'occupation 1'},
    {name: 'George', occupation: 'occupation 2'},
    {name: 'Jeck', occupation: 'occupation 3'},
    {name: 'Paula', occupation: 'occupation 1'},
    {name: 'Scruath', occupation: 'occupation 3'}
];

HTML:

<input type="text" ng-model="query">
<div ng-repeat="(key, occupation) in contacts | groupBy: 'occupation'">
    <p ng-bind="occupation[0].occupation"></p>
    <div>
        <div ng-repeat="contact in occupation | filter:search">
            <p ng-bind="::contact.fullName"></p>
            <p ng-bind="::contact.email"></p>
        </div>
    </div>
</div>

RESULT:

Occupation Name: "occupation 1"

  • name: "John"
  • name: "Paula"

Occupation Name: "occupation 2"

  • name: "George"

Occupation Name: "occupation 3"

  • name: "Jeck"
  • name: "Scruath"

Any thoughts?

There are two solution to your problem:

  • Use ng-show on the filtered array.
  • Use the sorting on the top ng-repeat .

Live example on jsfiddle .

 angular.module('ExampleApp', ['angular.filter']) .controller('ExampleController', function($scope) { $scope.contacts = [{ name: 'John', occupation: 'occupation 1' }, { name: 'George', occupation: 'occupation 2' }, { name: 'Jeck', occupation: 'occupation 3' }, { name: 'Paula', occupation: 'occupation 1' }, { name: 'Scruath', occupation: 'occupation 3' }]; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.js"></script> <div ng-app="ExampleApp"> <div ng-controller="ExampleController"> <input type="text" ng-model="query"> <h3> Filter with new array filtered </h3> <div ng-repeat="(key,occupation) in contacts| groupBy: 'occupation'" ng-show="filterOccupation.length"> <p ng-bind="key"></p> <div> <div ng-repeat="contact in filterOccupation = (occupation|filter:query)"> <p ng-bind="::contact.name"></p> </div> </div> </div> <h3> Filter with extra filtered </h3> <div ng-repeat="(key,occupation) in contacts|filter:query | groupBy: 'occupation'"> <p ng-bind="key"></p> <div> <div ng-repeat="contact in occupation|filter:query "> <p ng-bind="::contact.name"></p> </div> </div> </div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM