【问题标题】:Angular js filtering an object by textbox inputAngular js通过文本框输入过滤对象
【发布时间】:2017-04-01 18:59:16
【问题描述】:

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

<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;
    };

【问题讨论】:

  • 我现在意识到我需要将对象转换为数组。我只需要名称键。有什么想法吗?

标签: angularjs filtering


【解决方案1】:

您可以使用角度过滤器,并使用 ng-model 变量作为过滤器

<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>

【讨论】:

  • 谢谢萨吉塔兰。我必须有其他东西是关闭的,因为这对我不起作用。我在想也许自定义过滤器可能是要走的路。我也没有让自定义过滤器工作,因为我相信我无法访问其中的范围。有什么想法吗?
  • 我发现了部分问题——我实际上是在尝试过滤一个对象,我需要 result.name 作为回报。我更新了我的问题以反映这一点。
猜你喜欢
  • 2016-09-27
  • 2021-11-02
  • 1970-01-01
  • 2020-07-25
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
相关资源
最近更新 更多