我尝试在搜索字段中使用空格(例如:姓氏)过滤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>发布于 2017-03-22 07:19:26
编写一个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;
}
};
})发布于 2017-03-22 07:55:13
这是一个带工作示例的柱塞:
http://plnkr.co/edit/XNMhaPs7gcBDvU0xZm0l
我没有做太多的改变,它只是起作用了。这是JSON对象属性和值中的空格。希望这能有所帮助!
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"}
];
});https://stackoverflow.com/questions/42939888
复制相似问题