AngularJS - JSON并返回所有结果

时间:2014-07-04 12:21:36

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-click

我正在尝试使用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

0 个答案:

没有答案