[英]Angular filter array of an array
在過去的幾天里,我遇到了使用Angular過濾數組數組並顯示它的困難。 我試過搜索類似的帖子,但我無法找到解決方案。
示例我的數據如何顯示:
$scope.answers = [
{title: "Qestion1", keywords: ["dino", "dog", "cat"]},
{title: "Quessstion2", keywords: ["cat", "dog"]}
];
目前我正在顯示一個列表:
<div class="solution-box" ng-repeat="answer in pagedItems[currentPage]">
我有兩個搜索字段:
<input type="text" ng-model="title" ng-change="search1()" class="form-control" placeholder="Filter by title">
<input type="text" ng-model="keys" ng-change="search2()" class="form-control" placeholder="Filter by keywords">
Search1()函數正常工作:
$scope.search1 = function () {
$scope.filteredItems = $filter('filter')($scope.answers, function (answer) {
if (searchMatch(answer.title, $scope.title))
return true;
return false;
});
$scope.currentPage = 0;
// now group by pages
$scope.groupToPages();
};
Search2()函數不會改變filteredItems
$scope.search2 = function () {
$scope.filteredItems = $filter('filter')($scope.answers, function (answer) {
return $filter('filter')(answer.keywords, function (keyword) {
if (searchMatch(keyword, $scope.keys)) {
console.log($scope.filteredItems + '/' + keyword + '|' + $scope.keys);
return true;
}
return false;
});
});
$scope.currentPage = 0;
// now group by pages
$scope.groupToPages();
};
任何人都可以在Search2()函數中給出提示可能出錯的提示嗎? 當我正在記錄filteredItems時,它會記錄正確數量的答案,但列表仍然保持與原來相同的大小。 我在這里缺少自定義過濾器的主要邏輯是什么?
謝謝,
正如@mgilson所指出的那樣,你需要從過濾器回調函數中返回一個布爾值,但是你將返回一個總是很簡單的數組。 這里也沒有必要使用$filter('filter')
。 你可以這樣做:
$scope.filteredItems = $scope.answers.filter(function(answer) {
var matches = answer.keywords.filter(function() {
return searchMatch(keyword, $scope.keys);
});
return matches.length > 0;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.