使用 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
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.
ringa_lee2017-05-15 17:04:05
Becauseng
默认把你product
里三个字段key
,name
,is_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