我正在尝试使用AngularJS编写基本搜索功能。我编写了一个服务来查找我的JSON文件并将其绑定到$scope
对象$scope.SearchResult
我想要做的是在用户输入字符串时对SearchResult
内的项目执行搜索。对于找到的任何匹配项,请返回整个内容。
HTML:
<div ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<input ng-model="searchText">
<button ng-click="performSearch(searchText)">Submit</button>
{{ item }}
</div>
JS:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.SearchResult = [
{
"Index":1,
"Title":"Help",
"Snippet":"You found Mr Happy",
"Url":"www.test.co.uk"
},
{
"Index":2,
"Title":"Conatct",
"Snippet":"You found Mr Happy",
"Url":"www.test.co.uk"
},
{
"Index":3,
"Title":"Help",
"Snippet":"You found Mrs Angry",
"Url":"www.test.co.uk"
},
{
"Index":4,
"Title":"Help",
"Snippet":"You found Mr Sad",
"Url":"www.test.co.uk"
}
];
$scope.performSearch = function(searchText) {
console.log("Performing a search....");
angular.forEach($scope.SearchResult.Snippet, function(item) {
if( item.label.indexOf(searchText) >= 0 ) filtered.push(item);
console.log(item);
});
}
});
因此,如果在输入字段中输入了HAPPY,则会找到并显示2个匹配项。
Heres a plunker:http://plnkr.co/edit/mOjcYUbFpoveaDw12NjE?p=preview