过滤Angular JS中逗号分隔的多个值

时间:2017-08-22 20:12:15

标签: javascript html angularjs

我创建了一个过滤器,可根据在搜索字段中输入的输入值(单值)搜索视图数据。

控制器 -

patchingApp.controller('patchingController', function ($scope, $state, patchingServices, Excel, $timeout) {
    'use strict';

    $scope.searchData   = '';
    $scope.searchForm  = {};

查看 -

    <div class="row">
        <div class="col-md-10">
            <span class="search-filter"> On-Screen Filter: <input ng-model="searchText" /></span>
        </div>
    </div>

    <tbody class="tbody-class">
            <tr ng-repeat="patching in main_data_table.message | filter:searchText" >

新要求 - 我应该能够在搜索字段中输入多个以逗号分隔的值。

示例 - {patch,debug}

1 个答案:

答案 0 :(得分:0)

您可以编写自定义过滤器来执行此操作。根据您的要求修改以下代码

var app = angular.module('store', []);
    app.controller('StoreController', ['$scope', function($scope) {
    $scope.searchText="";
        $scope.friends = [{
            name: 'John'
        }, {
            name: 'Mary'
        }, {
            name: 'Mike'
        }, {
            name: 'Adam'
        }, {
            name: 'Julie'
        }, {
            name: 'Juliette'
        }];
        
        
    }]);
    
 app.filter('fill', function() {
  return function(input,val) {
  if(val!=undefined){
     var out=[];
     var filterVal = val.split(",");
                if (filterVal.length > 1) {
                    for (var i = 0; i < filterVal.length; i++) {
                     for(var j=0;j<input.length;j++){
                        if (input[j].name == filterVal[i])                                   out.push(input[j]);
                    }
                     }
                     return out;
                }
  }
  }


});
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-filter-filter-production</title>
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  
</head>
<body ng-app="store" ng-controller="StoreController">

<label>Search: <input ng-model="searchText"></label>
<table id="searchTextResults">
  <tr><th>Name</th></tr>
  <tr ng-repeat="friend in friends" ng-if="searchText.indexOf(',')==-1">
    <td>{{friend.name}}</td>
  </tr>
    <tr ng-repeat="friend in friends | fill:searchText track by $index" ng-if="searchText.indexOf(',')>-1">
    <td>{{friend.name}}</td>
  </tr>
</table>

</body>
</html>