【发布时间】:2016-08-03 09:15:42
【问题描述】:
我已经建立了一个基于this post 的过滤器。 问题在于,在某些对象中,我的属性可以同时具有多个值(值数组)(例如,一种葡萄酒可以同时属于“葡萄酒”和“香槟”类别) .我一直在尝试修改过滤器,但没有成功。这是我的html:
<div ng-controller="myCtrl">
<div ng-repeat="(prop, ignoredValue) in wines[0]" ng-init="filter[prop]={}">
<b>{{prop}}:</b><br />
<span class="quarter" ng-repeat="opt in getOptionsFor(prop)">
<b><input type="checkbox" ng-model="filter[prop][opt]" /> {{opt}}</b>
</span>
<hr />
</div>
<div ng-repeat="w in filtered=(wines | filter:filterByProperties)">
{{w.name}} ({{w.category}})
</div>
还有我的角度逻辑:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.wines = [
{ name: "Wine A", category: ["red"] },
{ name: "Wine B", category: ["red"] },
{ name: "wine C", category: ["white"] },
{ name: "Wine D", category: ["red"] },
{ name: "Wine E", category: ["red"] },
{ name: "wine F", category: ["champagne","white"] },
{ name: "wine G", category: ["champagne"]},
{ name: "wine H", category: ["champagne"] }
];
$scope.filter = {};
$scope.getOptionsFor = function (propName) {
return ($scope.wines || []).map(function (w) {
return w[propName];
}).filter(function (w, idx, arr) {
return arr.indexOf(w) === idx;
});
};
$scope.filterByProperties = function (wine) {
// Use this snippet for matching with AND
var matchesAND = true;
for (var prop in $scope.filter) {
if (noSubFilter($scope.filter[prop])) continue;
if (!$scope.filter[prop][wine[prop]]) {
matchesAND = false;
break;
}
}
return matchesAND;
};
function noSubFilter(subFilterObj) {
for (var key in subFilterObj) {
if (subFilterObj[key]) return false;
}
return true;
}
});
我想让它工作,所以当一个对象的属性具有一个以上值的数组时(如示例中的白色和香槟色),只需选择其中一个(或两者)即可选择该对象.提前致谢。
我已经更新了 JsFiddle here
【问题讨论】:
标签: javascript angularjs