简体   繁体   中英

Filter multiple values separated by a comma in Angular JS

I have created a filter that searches the view data based on the input value(Single value) entered in the search field.

Controller -

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

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

View -

    <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" >

New Requirement - I should be able to enter multiple values in the search field separated by a comma.

Example - {patch, debug}

You can write a custom filter to do this. Modify the below code to your requirements

 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> 

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