【发布时间】:2018-10-30 10:10:25
【问题描述】:
我正在尝试使用简单的数组列表过滤数组,但我似乎无法弄清楚如何,我尝试使用自定义过滤器但无法使其工作。 编辑:我添加了更多代码。文本框搜索工作正常,但是当我在 ng-repeat 上添加 myFilterby 时,它不再过滤。我只是想过滤掉一个数组列表。
<div class="input-group">
<input type="text" class="form-control" placeholder="Search .." ng-model="searchText">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
<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>
角度:
var HandleModule = angular.module("HandleModule",['rzModule','ui.bootstrap','angular.filter']);
HandleModule.controller('HandleCtrl',function($scope,$http){
// get data from the server in JSON format
$scope.chk0 = ['apple', 'orange', 'banana'];
$http.get('./loader.php').then(successCallback, errorCallback);
function successCallback(response){
//success code
$scope.product = response.data;
}
function errorCallback(error){
//error code
$scope.product="error";
}
$scope.myFilterBy = function(e) {
return $scope.chk0.indexOf(e) !== -1;
}
PHP:
<?php
$con = mysqli_connect("localhost","root","","product");
$query = "SELECT id, model, brand, price, description, image, FROM fruits ORDER BY id";
$result = mysqli_query($con, $query);
$fruits= array();
while($row = mysqli_fetch_assoc($result))
{
$fruits[] = $row;
}
echo json_encode($fruits);
?>
使用 NG-repeat 分别打印出数据。我使用 ng-repeat 在 html 上显示
<p ng-repeat="a in products ">
{{a}}
{"id":"1","model":"test1","brand":"orange","price":"4",
"description":"orange sweet and sour","image":"orange.jpg"}
{"id":"2","model":"test2","brand":"banana","price":"3",
"description":"yellow sweet","image":"banana.jpg"}
{"id":"3","model":"test3","brand":"apple","price":"5",
"description":" red sweet crunchy","image":"apple.jpg"}
【问题讨论】:
-
请在您的问题中包含产品数组的定义。
-
您能否将
product和searchText添加到您的问题中? -
myFilterBy的参数e将是一个对象(如ng-repeat中的a)。您应该将其属性之一传递给indexOf而不是自己传递:return $scope.chk0.indexOf( e.somePropertyProbablyModel ) !== -1; -
@jbrown 产品数组来自 mysql 表。它在没有 myFilterBy 函数的情况下完美加载。
-
@Claies searchText 只是一个从列表中搜索的文本框,它可以正常工作而无需添加额外的过滤器 myFilterBy(当我这样做时它什么也不加载。)
标签: javascript angularjs