AngularJS中如何用数组列表结合ng-repeat实现数组过滤?
搞定基于数组列表的AngularJS过滤问题
嘿,我一眼就看出你的问题出在哪儿了——自定义过滤器myFilterBy的逻辑不对!
你现在的过滤器里,e是product数组里的整个商品对象(比如{"id":"1","model":"test1","brand":"orange",...}),但$scope.chk0是个字符串数组(['apple', 'orange', 'banana']),直接用indexOf(e)肯定找不到匹配项啊,对象和字符串根本不是一回事儿,所以过滤器把所有商品都过滤掉了,自然看起来失效了。
快速修复自定义过滤器
把过滤器改成检查商品的brand属性是否在chk0数组里就行,修改后的代码如下:
$scope.myFilterBy = function(productItem) { // 只保留brand在chk0列表里的商品 return $scope.chk0.indexOf(productItem.brand) !== -1; }
几个额外的小优化
- 兼容空数组场景:如果以后
chk0可能清空,加个判断让空数组时显示所有商品会更友好:
$scope.myFilterBy = function(productItem) { // 数组为空时不做过滤 if ($scope.chk0.length === 0) return true; return $scope.chk0.indexOf(productItem.brand) !== -1; }
- 修正PHP的SQL语法错误:你的SQL语句里
image, FROM多了个逗号,这会导致数据库查询失败,赶紧改了:
$query = "SELECT id, model, brand, price, description, image FROM fruits ORDER BY id";
- 统一变量名:你单独测试ng-repeat时写的是
ng-repeat="a in products ",但控制器里赋值的是$scope.product = response.data;,变量名多了个s,虽然可能是笔误,但统一起来能避免莫名其妙的问题。
验证修复效果
修改后,你的ng-repeat代码就能正常工作了:
<td ng-repeat="a in product | filter:searchText | filter:myFilterBy"> <img class="avatar" src="img/{{a.image}}" alt=""> <div class="middleT"> <p>{{a.brand}} {{a.model}}</p> <p>${{a.price}}</p> </div> </td>
现在既能用文本框搜索商品,又能只显示品牌在chk0列表里的商品啦!
内容的提问来源于stack exchange,提问作者Lundy Lundy
相关产品推荐
相关产品推荐

