如何使用此AngularJS
结构将json
过滤器用于搜索功能?
$scope.jsonObj = {
idNo1: {
name: "Diljish",
age: 24
},
idNo2: {
name: "Shemeem",
age: 28
}
}
答案 0 :(得分:2)
不需要JavaScript代码。
您应该为要过滤的数据创建input
:
Filter: <input type="text" ng-model="yourFilter.name"/>
然后,在ng-repeat
:
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr ng-repeat="person in persons | filter:yourFilter | orderBy:'name'">
<td>{{ person.name | uppercase}}</td>
<td>{{ person.age | lowercase}}</td>
</tr>
</table>
persons
是json
对象。
(function()
{
var yourController=function($scope) {
$scope.persons= [];
function init() {
$scope.persons={
idNo1: {
name: "Diljish",
age: 24
},
idNo2: {
name: "Shemeem",
age: 28
}}
}
init();
};
yourController.$inject=['$scope'];
angular.module('yourApp').controller('yourController',
yourController);
}());
<强>更新强>
如果您使用另一个json
对象,它仍然是相同的:
<body ng-init="people=[{ name:'Shemmem' }, { name:'Diljish' }]">
Filter: <input type="text" ng-model="yourFilter.name"/>
<table>
<tr>
<td>Name</td>
<td>City</td>
</tr>
<tr ng-repeat="person in people | filter:yourFilter">
<td>{{ person.name }}</td>
<td>{{ person.city }}</td>
</tr>
</table>
</body>
答案 1 :(得分:1)
如果你想在ng-repeat中过滤它,你可以使用带管道的过滤器&#34; |&#34;:
<div ng-repeat="person in people | filter: customFilter">
</div>
&#13;
然后,在控制器中定义customFilter:
$scope.customfilter = function (person) {
return (person.name == $scope.nameToBeFiltered)}
&#13;
其中&#34; nameToBeFiltered&#34;是您要过滤的名称(您可以将该范围变量建模到视图中的输入)。
现在,如果你想在其他地方过滤,也许你正在寻找一个&#34; Javascript:在Json中找到价值&#34;而不是AngularJS。
答案 2 :(得分:0)
答案 3 :(得分:0)
请找到工作代码。
已过滤&#34; name&#34;
(function(angular) {
'use strict';
angular.module('app', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.filtertext="";
$scope.jsonObj = {
idNo1: {
name: "Diljish",
age: 24
},
idNo2: {
name: "Shemeem",
age: 28
}
}
$scope.filterByName = function(items,filtertext) {
var result = {};
angular.forEach(items, function(value, key) {
if (value.name.toLowerCase().indexOf(filtertext) > -1) {
result[key] = value;
}
});
return result;
}
}]);
})(window.angular);
&#13;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-select-with-default-values-production</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
</head>
<body ng-app="app">
<div ng-controller="ExampleController">
<input type="text" ng-model="filtertext"/>
<hr>
<div ng-repeat="(k,v) in filterByName(jsonObj,filtertext)">
{{k}} {{v.name}}
</div>
</div>
</body>
</html>
&#13;