条件过滤列表显示在angularjs中

Conditional filtering list displayed in angularjs

本文关键字:angularjs 列表显示 过滤 条件      更新时间:2023-09-26

当我试图有条件地筛选用ng重复显示的列表时,我遇到了一个问题:如果搜索词以#开头:按books仅筛选/else:按username仅筛选

这是我的确切问题的代码笔:

http://codepen.io/prettyGoodPancakes/pen/raoWeB

我的清单如下:

$scope.users = [
{
  username: 'clem',
  books: [
    { value: 'kafka' },
    { value: 'maupassant' }
  ]
},
{
  username: 'sam',
  books: [
    { value: 'Balzac' },
    { value: 'Zola' },
    { value: 'Kafka' }
  ]
}
];

以下是在这个网站上运行的相同代码片段:

angular.module('ionicApp', ['ionic'])
.controller('MyCtrl', function($scope) {
  $scope.users = [{
    username: 'clem',
    books: [{
      value: 'kafka'
    }, {
      value: 'maupassant'
    }]
  }, {
    username: 'sam',
    books: [{
      value: 'Balzac'
    }, {
      value: 'Zola'
    }, {
      value: 'Kafka'
    }]
  }];
  $scope.$watch(function() {
    return $scope.search;
  }, function() {
    if (scope.search.length > 0) {
      if ($rootScope.search[0] === '#') {
        // Filter ONLY by books
      } else {
        // Filter ONLY by username
      }
    }
  }, true);
});
body {
  cursor: url('http://ionicframework.com/img/finger.png'), auto;
}
<html ng-app="ionicApp">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>Ionic List Directive</title>
  <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
  <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body ng-controller="MyCtrl">
  <ion-header-bar class="bar bar-header item-input-inset">
    <label class="item-input-wrapper">
      <i class="icon ion-ios7-search placeholder-icon"></i>
      <input type="search" placeholder="Search" ng-model="search">
    </label>
    <button class="button button-clear">
      Cancel
    </button>
  </ion-header-bar>
  <ion-content>
    <!-- The list directive is great, but be sure to also checkout the collection repeat directive when scrolling through large lists -->
    <ion-list>
      <ion-item ng-repeat="user in users | filter:search" item="item">
        {{user.username}}
        <p><span ng-repeat="game in user.books" style="margin-right:5px">{{game.value}}</span>
        </p>
      </ion-item>
    </ion-list>
  </ion-content>
</body>
</html>

创建自定义过滤器:

.filter('PrettyGoodPancakeFilter', function () {
  return function(items, filterBy) {
    if (filterBy.indexOf('#') === 0) {
      return items.filter(function (item) {
        return item.username.indexOf(filterBy) > -1;
      });
    } else { 
      // filter by books
    }
  }
});