【问题标题】:Filtering not working in angular js template过滤在角度 js 模板中不起作用
【发布时间】:2015-08-28 13:10:12
【问题描述】:

我想根据多个字段过滤结果。

HTML

<input type="text" ng-model="query">

<ul>
  <li ng-repeat="x in phones | filter: search | orderBy:orderProp" >
    <span>{{x.name}}</span>
    <p> {{ x.id}} </p>
    <p> {{ x.age}} </p>
  </li>

</ul>

在我提到的控制器中,

$scope.search = function (item) {

          return ( (item.name.indexOf($scope.query || '') ) !== -1 || (item.id.indexOf($scope.query || '')) !== -1);

    };

Plnkr:http://plnkr.co/edit/a1khZS9RcFdgitTYPgqs?p=preview

为什么过滤器不起作用? PS:我在 firebug 中收到错误“TypeError: href is null”。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您的搜索功能出现错误。

    item.id.indexOf 不是函数

    你得到这个是因为 item.id 是一个整数文字。

    您可以先尝试转换 id.toString(),或者将查询解析为整数。

    $scope.search = function(item) {
    
      return ((item.name.indexOf($scope.query || '')) !== -1 || (item.id.toString().indexOf($scope.query || '')) !== -1);
    
    };
    

    Here 是一个工作示例。匹配区分大小写,因此请记住这一点。

    【讨论】:

      【解决方案2】:

      只需替换:

      <li ng-repeat="x in phones | filter: search| orderBy:orderProp" >
      

      与

      <li ng-repeat="x in phones | filter: query | orderBy:orderProp" >
      

      (您的范围属性的名称是query,而不是search)。

      【讨论】:

      • 当然会成功。但我想按多个字段过滤。看一看:stackoverflow.com/questions/13216115/…
      • 我相信他是想提供一个过滤功能。
      • 好吧,我误解了你需要什么。 Michael G 在他的回答中有一个适当的解决方案
      【解决方案3】:

      像这样更改 list.html 的代码。您必须通过过滤器传递文本框的 ng-model

      <div class="container">
      
          <input type="text" ng-model="query">
      
          <ul>
            <li ng-repeat="x in phones | filter: query | orderBy:orderProp" >
              <span><a ng-href="#/phones/{{x.id}}">{{x.name}}</a></span>
              <p> {{ x.id}} </p>
              <p> {{ x.age}} </p>
            </li>
      
          </ul>
      
       </div>
      

      【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2016-03-13
      • 1970-01-01
      • 2018-05-04
      • 2016-10-05
      • 1970-01-01
      相关资源
      最近更新 更多