search

Home  >  Q&A  >  body text

angular.js - AngularJS filter:search 是如何匹配的 ng-repeat filter:search

使用 angularJS 来进行测试,ng-reapt="pro in products | filter:search" 一个特别大的疑问
如下的这个测试,为什么 search 输入框中,输入 a也会有结果

测试代码:

<!DOCTYPE html>
<html>

<head>
  <script data-require="angularjs@1.5.5" data-semver="1.5.5" src="https://code.angularjs.org/1.5.5/angular.js"></script>
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
</head>

<body>

  <script>
    var data = {
      "products": [{
        "key": "KEY1",
        "name": "iPhone6S",
        "is_in_presale": false
      }, {
        "key": "KEY2",
        "name": "iPhone7",
        "is_in_presale": true
      }],
      "activities": []
    };

    var cartApp = angular.module('cartApp', []);
    cartApp.controller('ProductListCtrl', function($scope, $http) {

      $scope.dump = function(input) {
        console.log(input);
      }
      $scope.products = data.products;
      //            $scope.change();
    });
  </script>


  <p ng-app="cartApp" ng-controller="ProductListCtrl">
    <input type="text" ng-model="search">
    <p style="clear: both"></p>

    <p class="" style="float: left;width: 20%">
      <h1>repeat</h1>
      <ol>
        <li ng-repeat="pro in products"> {{pro.name}} - {{pro.key}}</li>
      </ol>
    </p>
    <p class="" style="float: left;">
      <h1>normalProduct</h1>
      <ol>
        <li ng-repeat="pro in products | filter:search as result">{{pro.name}} - {{pro.key}}</li>
      </ol>
    </p>
    {{dump(result)}}

  </p>

</body>


</html>

测试地址

http://plnkr.co/edit/wZIOF1uAvEgB9UPD1EnW?p=preview

伊谢尔伦伊谢尔伦2745 days ago568

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-15 17:04:05

    When you do not specify which field to filter, the default filter will match the values ​​of all fields. When you enter a, angular should convert false into a string by default, and a matches false. If you change the filter conditions to this

    <li ng-repeat="pro in products | filter:{name:search}">{{pro.name}} - {{pro.key}}</li>

    If you type a, there will be no results. What it means is that only the value of the name field is filtered.

    reply
    0
  • ringa_lee

    ringa_lee2017-05-15 17:04:05

    Becauseng默认把你product里三个字段keynameis_in_presale都转成字符串和你的输入去比较了,所以a其实匹配到的是false里的a。你可以试试输入true, I can feel the difference in results.

    If you need to specify fields for filter, please refer to the document:

    Or just look at my plunker

    reply
    0
  • Cancelreply