首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对带有空格的JSON属性应用搜索筛选器?

问如何对带有空格的JSON属性应用搜索筛选器?
EN

Stack Overflow用户
提问于 2017-03-22 07:08:26
回答 2查看 1.3K关注 0票数 0

我尝试在搜索字段中使用空格(例如:姓氏)过滤json属性,我可以使用空格访问和打印JSON属性,但无法使用空格过滤JSON属性。如何在搜索字段中使用空格对JSON属性应用筛选?

​

代码语言:javascript
复制
        <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>
EN

回答 2

Stack Overflow用户

发布于 2017-03-22 07:19:26

编写一个custom AngularJS filter并对搜索文本使用JavaScript的.trim()函数。

示例:

代码语言:javascript
复制
 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;
       }
    };
})
票数 0
EN

Stack Overflow用户

发布于 2017-03-22 07:55:13

这是一个带工作示例的柱塞:

http://plnkr.co/edit/XNMhaPs7gcBDvU0xZm0l

我没有做太多的改变,它只是起作用了。这是JSON对象属性和值中的空格。希望这能有所帮助!

index.html

代码语言:javascript
复制
<!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

代码语言:javascript
复制
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"}        
    ];       

});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42939888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档