问题
I am using isteven-multi-select to output an array of objects from a select element's multiple selections.
[ { category: "Adventure", ticked: true }, { category: "Strategy", ticked: true } ]
2. Then using angular.forEach to change the array of objects into an array of the category values.
$scope.testOutput = function () {
angular.forEach($scope.output, function(value, prop, obj) {
var categoryFiltered = [];
categoryFiltered.push(value.category);
console.log(categoryFiltered);
});
};
categoryFiltered = ["Adventure", "Strategy"];
3. Now I need to use the categoryFiltered array to filter out the other categories in an ng-repeat.
HTML
ul
li(ng-repeat='item in items | filter: {categories: categoryFiltered')
MongoDB populating items
{
year: 1962,
categories: ["Adventure"]
}, {
year: 1972,
categories: ["Fishing"]
}, {
year: 1982,
categories: ["Strategy"]
}
What is the best way to achieve this?
回答1:
Write a custom filter, then you can filter the categories however you like (eg. do you want to filter items that match ALL the categories specified? Or only some?).
Here's a plunkr example: http://plnkr.co/edit/Lv11QWumN7ktjfS15RpY?p=preview
Main part of it, to define your filter:
app.filter('filterByCategories', function() {
return function(input, categories) {
// Input is the array to be filtered, categories is the list of
// categories to filter by
input = input || [];
categories = categories || [];
var output = [];
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < categories.length; j++) {
// If input matches any of the categories, then add it to the list
if (input[i].categories.indexOf(categories[j].trim()) >= 0) {
output.push(input[i]);
break;
}
}
}
return output;
};
})
Then you can use the custom filter like so:
<li ng-repeat="item in data | filterByCategories: filterStr.split(',')">
Or:
<li ng-repeat="item in data | filterByCategories: ['Adventure', 'Strategy']">
来源:https://stackoverflow.com/questions/31628519/using-filter-to-create-array-then-using-that-array-to-filter-ng-options