【问题标题】:AngularJS Ng-Repeat Search Filter, How can i limit what properties to search for?AngularJS Ng-重复搜索过滤器,我如何限制要搜索的属性?
【发布时间】:2017-01-09 16:37:16
【问题描述】:

目前我有一个 ng-repeat,每行写出一个相当大的对象。但是,我只希望搜索过滤器扫描 5 个属性,而不是对象具有的 20 个属性。有没有办法告诉过滤器只检查特定的属性而忽略其余的?我在想下面的东西......

<div> <input ng-model="search" type="text"/> </div>
<div ng-repeat="item in items | filter:search:property1:property2">
   {{item.property1}}
</div>

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    创建一个自定义过滤器,让您可以根据需要拥有必要的参数。

    app.filter('myFilter', function(){
      // Just add arguments to your HTML separated by :
      // And add them as parameters here, for example:
      // return function(dataArray, searchTerm, argumentTwo, argumentThree) {
      return function(dataArray, searchTerm) {
          // If no array is given, exit.
          if (!dataArray) {
              return;
          }
          // If no search term exists, return the array unfiltered.
          else if (!searchTerm) {
              return dataArray;
          }
          // Otherwise, continue.
          else {
               // Convert filter text to lower case.
               var term = searchTerm.toLowerCase();
               // Return the array and filter it by looking for any occurrences of the search term in each items id or name. 
               return dataArray.filter(function(item){
                  var termInId = item.id.toLowerCase().indexOf(term) > -1;
                  var termInName = item.name.toLowerCase().indexOf(term) > -1;
                  return termInId || termInName;
               });
          } 
      }    
    });
    

    然后在 HTML 中

    <tr ng-repeat="item in data | myTableFilter:filterText:argumentTwo:argumentThree">
    

    灵感来自filter-by-multiple-columns-with-ng-repeat

    【讨论】:

    • 我试试看!
    【解决方案2】:

    不确定你可以直接做。我认为您必须在控制器中编写一个函数才能做到这一点。

    例如

        <div> <input ng-model="search" type="text"/> </div>
        <div ng-repeat="item in items | filter:searchSpecificPpts()">
           {{item.property1}}
        </div>
    
    in your controller create a function like
       $scope.searchSpecificPpts(){
          //Here goes the logic to filter
          return filteredList;
       }
    

    【讨论】:

    • 我使用这种方法遇到的问题是我无法获取用户正在搜索的文本以进行任何比较。
    • 您正在使用用户输入 ng-model="search" 所以在 $scope.searchSpecificPpts() 函数中将其用作 $scope.search .. 您将可以访问该属性。
    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2014-10-12
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多