2016-11-18 174 views
0

我真的很陌生,所以这可能超级简单,但我似乎无法让它工作。我有一个应用程序,它有一个搜索字段,需要在用户输入时主动筛选结果。我所有的数据都在searchResults对象中。当我输入文本框时没有任何反应。我错过了什么?在此先感谢您的帮助。角度js通过文本框输入过滤对象

<div> 
    <input ng-model="query" name="search" id="search" type="text" placeholder="search by product or category"> 
    <ul id="filteredResults" ng-if="results.length"> 
     <li ng-repeat="result in results | filteredSearchFilter | limitTo: 10">{{result.name}}</li> 
    </ul> 
</div> 

filteredSearch.filter.js

module.exports = function() { 
    return function(data, keys, query) { 
     results = []; 
     if(!query){ 
     return data; 
     } else { 
     angular.forEach(data, function(obj){ 
      var matched = false; 
      angular.forEach(keys, function(key){ 
       if(obj[key]){ 
        // match values using angular's built-in filter 
        if ($filter('filter')([obj[key]], query).length > 0){ 
        // don't add objects to results twice if multiple 
        // keys have values that match query 
        if(!matched) { 
         results.push(obj); 
        } 
        matched = true; 
        } 
       } 
      }); 
     }); 
     } 
     return results; 
    }; 
+0

我实现现在我需要将对象转换为数组。我只需要名称键。有任何想法吗? – luigilife

回答

0

可以使用角度滤波器,和使用NG-模型变量作为滤波器

<li ng-repeat="result in results | filter:query"> 
    <div> 
     {{result .firstname}} {{result .lastname}} 
    </div> 
</li> 

angular.module('myApp', []) 
 
    .controller('myCtrl', function($scope){ 
 
    
 
    $scope.results = [ 
 
    
 
    {firstname: 'john', lastname: 'smith'}, 
 
    {firstname: 'jane', lastname: 'due'}, 
 
    {firstname: 'bob', lastname: 'rand'} 
 
    
 
    ]; 
 
    
 
});
<!DOCTYPE html> 
 
<html ng-app='myApp'> 
 
<head> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> 
 
    <meta charset="utf-8"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body ng-controller='myCtrl'> 
 
    <div> 
 
    <div> 
 
     <input type="text" placeholder="Search" ng-model="query"> 
 
    </div> 
 
    </div> 
 

 
<ul> 
 
    <li ng-repeat="result in results | filter:query"> 
 
<div> 
 
    {{result .firstname}} {{result .lastname}} 
 
</div> 
 
</li> 
 
</ul> 
 

 
</body> 
 
</html>

+0

谢谢Sajeetharan。我必须拥有其他的东西,因为这不适合我。我在想,也许一个自定义过滤器可能是一条路。我还没有得到自定义过滤器的工作,因为我相信我不能访问它的范围。有关于此的任何想法? – luigilife

+0

我想出了我的问题的一部分 - 我实际上正在尝试过滤一个对象,并且我需要返回result.name。我更新了我的问题以反映这一点。 – luigilife