【问题标题】:Weird bug: AngularJS can search single fields but not multiple fields奇怪的错误:AngularJS 可以搜索单个字段但不能搜索多个字段
【发布时间】:2015-12-27 01:58:35
【问题描述】:

我正在使用 Angular 1.3 编写应用程序。我想通过任何单词/字段搜索表格;一个搜索框搜索所有内容。

目前,我可以通过以下方式让我的搜索框通过特定字段进行搜索:

<label>Search: <input ng-model="searchKeyword.title"></label>

<label>Search: <input ng-model="searchKeyword.author"></label>

那些工作正常。但是,当我尝试同时搜索所有字段时:

<label>Search: <input type = "text" ng-model="searchKeyword"></label>

它根本不起作用。

这是我在桌子上的代码:

  <label>Search: <input ng-model="searchKeyword"></label>

  <table ng-repeat="post in posts | orderBy: sort | filter: searchKeyword">
    <tr>
       <td> {{post.title}} </td>

       <td> {{post.author}} </td>

       <td> {{post.content}} </td>

       <td> {{post.date | date: "d/M/yyyy"}} </td>
    </tr>
  </table>

这是在我的主控制器内部:

 $scope.posts = posts.posts;
 $scope.searchKeyword = "";

请告诉我究竟是什么导致了这个奇怪的错误。谢谢。

【问题讨论】:

  • 我似乎无法在这里重现问题,当我测试它时,它可以正常工作。

标签: angularjs search angularjs-ng-repeat angular-ngmodel angular-filters


【解决方案1】:

这是因为 ng-repeat 创建了一个新作用域,不能写入其父作用域的原始属性。但可以写入其父作用域的对象。

作用域(典型地)从其父作用域继承属性。

这个post 很好地解释了它。你想要的是一个自定义过滤器检查ng-modal 对你对象中的每个属性。

. filter('customFilter', function() {
return function(product,query) {
  var out = [];


    angular.forEach(product,function(value,key){

    if(value['author'].indexOf(query)>-1 || value['title'].indexOf(query)>-1)
    {
                out.push(value)
    }
    })
  return out;
}
})

Here 是一个工作示例

【讨论】:

  • 谢谢。这真是一本好书。那么我能做些什么来解决这个问题呢?我试着做 ng-model="$parent.searchKeyword" 和 ng-model="posts.searchKeyword",都不管用! @Divya MV
  • 感谢您的示例。我理解这背后的逻辑。但是,当我这样做时,我得到 TypeError: Cannot read property 'indexOf' of undefined。而且我的帖子根本没有加载。为什么会发生这种情况? @Divya MV
【解决方案2】:

我发现这篇文章很晚。无论如何,我的建议可能对其他观众有所帮助。 以奇怪的方式解决奇怪的错误。

我发现这篇文章对use of multiple filters in controller with example的大数据表搜索非常有用。

(阅读以上链接后) 但是您不需要在表格的每一列中包含多个观察者和多个输入字段,对于您的场景,您只需要在静态 json 声明后更改以下代码。

$scope.$watch('searchKeyword', function(val) { $scope.items = $filter('filter')($scope.items2, val); });

考虑到 searchKeyword 是要搜索的输入字段的 ng-model。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2020-09-11
    • 2020-03-10
    • 1970-01-01
    • 2021-08-05
    • 2015-06-17
    • 2012-10-21
    相关资源
    最近更新 更多