元素中的角度ng重复条件换行项(ng-repeat group中的过滤项)

时间:2016-03-24 09:12:48

标签: javascript angularjs angularjs-ng-repeat

在某些职业中找不到过滤后的用户时,我试图隐藏职业名称。

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>

结果:

职业名称:&#34;职业1&#34;

  • 姓名:&#34; John&#34;
  • 姓名:&#34; Paula&#34;

职业名称:&#34;职业2&#34;

  • 姓名:&#34; George&#34;

职业名称:&#34;职业3&#34;

  • 姓名:&#34; Jeck&#34;
  • 姓名:&#34; Scruath&#34;

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的问题有两种解决方案:

  • 在已过滤的阵列上使用ng-show
  • 使用顶部ng-repeat的排序。

jsfiddle上的实例。

&#13;
&#13;
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'
    }];
  });
&#13;
<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>
&#13;
&#13;
&#13;