如何在带有空格的JSON属性上应用搜索过滤器?

时间:2017-03-21 23:08:26

标签: angularjs

我试图在搜索字段中使用空格(例如:姓氏)过滤json属性,我能够使用空格访问和打印JSON属性,但我无法使用空格过滤JSON属性空间。如何在搜索字段中使用空格对JSON属性应用过滤器?

        <div ng-init="jsonData()">   
            <table border="1" class="table table-striped">
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Age</th>

                    </tr>
                </thead>

                <tbody>
                    <tr ng-repeat="x in result | filter:searchText">
                        <td>{{x['First Name']}}</td>
                        <td>{{x['Last Name']}}</td>
                        <td>{{x.Age}}</td>
                    </tr>
                </tbody>
            </table>
        </div>

2 个答案:

答案 0 :(得分:0)

撰写custom AngularJS filter并在搜索文字上使用JavaScript的.trim()功能。

示例:

 angular.module('myModule', [])
    .filter('searchTextWithSpaces', function() {
       return function(array, searchText) {
          searchText = searchText.trim();
          array = array.filter(function(obj) {
               return obj["Last Name"].trim().indexOf(searchText) !== -1;
          });
          return array;
       }
    };
})

答案 1 :(得分:0)

这是一个带有工作示例的plunker:

http://plnkr.co/edit/XNMhaPs7gcBDvU0xZm0l

我没有做太多改动,只是起作用。 这是JSON Object属性和值中的空间。希望有所帮助!

<强>的index.html

<!doctype html>

<html lang="en" ng-app="app">
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
  <script src="scripts.js"></script>
</head>

<body ng-controller="SampleController">

    Search by Last Name
    <input type="text" ng-model="searchText">

    <table border="1" class="table table-striped">
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>

                </tr>
            </thead>

            <tbody>
                <tr ng-repeat="x in result | filter:searchText">
                    <td>{{x['first name']}}</td>
                    <td>{{x['last name']}}</td>
                </tr>
            </tbody>
        </table>

</body>
</html>

<强>的script.js

angular.module('app', []);

angular.module('app').controller('SampleController', function ($scope) {

    $scope.result = [
     {"first name": "John", "last name": "Doctor Watson"}, 
     {"first name": "Peter", "last name": "Doctor Who"}, 
     {"first name": "Sherlock", "last name": "Holmes"}, 
     {"first name": "James", "last name": "Moriarty"}        
    ];       

});