У меня есть следующая функция, которую я написал для фильтрации данных на основе ввода пользователя.
Контроллер
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;
}
});
HTML
<!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-модель неправильно связывается со значениями «имена» и «бренды» в функции. Точка в правильном направлении приветствуется.