我编写了以下函数,用于根据用户输入过滤数据。
var app = angular.module("viewJSON",[]);
app.controller("viewCtrl",function Hello($scope, $http) {
$http({
method: 'GET',
url: './data.json'
}).then(function (response){
$scope.products = response.data;
},function (error){
console.log("error");
});
var data=[];
$scope.filterData = function ($scope) {
if ($scope.names.length != 0 && $scope.brands.length != 0){
data.push(products.name.includes($scope.names) && products.brand.includes($scope.brands));
}else if($scope.names.length == 0 && $scope.brands.length != 0){
data.push(products.brand.includes($scope.brands));
}else if($scope.names.length != 0 && $scope.brands.length == 0){
data.push(products.name.includes($scope.names));
}
return data;
}
});
<!DOCTYPE html>
<html ng-app="viewJSON">
<head>
<link rel="stylesheet" href="home-page.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="home-page.js"></script>
</head>
<body ng-controller="viewCtrl">
<div class="wrap">
<div class="search" ng-innit="x=0">
<b>Product Name:</b> <input type="text" ng-model="names" class="searchTerm" ng-keydown="x = x+1"><br>
<b>Product Brand:</b> <input type="text" ng-model="brands" class="searchTerm" ng-keydown="x = x+1">
</div>
</div>
<div>
<table class="resultContent" ng-if="x > 0">
<tr>
<th>Brand</th>
<th>Name</th>
<th>Price</th>
<th>Retailer</th>
<th>Image</th>
</tr>
<tr id="rows" ng-repeat="item in filterData">
<td class="otherCol">{{ item.brand }}</td>
<td class="otherCol">{{ item.name }}</td>
<td class="otherCol">{{ item.price }}</td>
<td class="otherCol">{{ item.retailer }}</td>
<td class="imageCol"><img ng-src="{{ item.image_url}}"></td>
</tr>
</table>
</div>
</body>
</html>
我玩了一段时间,据我所知,该函数根据用户输入创建一个数组,然后使用ng-repeat显示该数组。我试过使用filterBy:filterData,尽管这给了我错误过滤器而不是数组,这使我感到困惑,因为filterData的输出是一个数组。我感觉ng-model不能正确绑定函数中的值'names'和'brands'。朝正确方向的观点将不胜感激。
答案 0 :(得分:0)
您没有看到任何结果的原因是您的filterData,因为filterData是一个函数,因此您必须使用以下语法来使用它。
ng-repeat="item in filterData()"
请注意括号的结尾。还请记住,在ng-repeat中使用函数不是一个好习惯,因为在每次DOM更新时都会调用该函数,并且会添加许多不必要的工作。我强烈建议您将过滤后的数据放入数组中,并在ng-repeat中使用该数组。