【发布时间】:2014-08-15 06:18:43
【问题描述】:
我想放这个过滤器:filter:'!Category' 像这样进入这个元素:
<div ng-repeat="(prop, ignoredValue) in wines[0] | filter:'!Category'" ng-init="filter[prop]={}">
但它不会过滤掉“类别”属性。但是,如果我在以下 ng-repeat 元素上放置一个类似的过滤器以排除“Wine”,它就可以正常工作:
<span class="quarter" ng-repeat="opt in getOptionsFor(prop) | filter:'!Wine'">
我不明白为什么我不能在这里过滤掉属性值。我对 angularjs 很陌生,我想弄清楚这一点。我想从对象中排除特定的属性名称。 “名称”或“类别”
我在下面链接了小提琴。非常感谢任何帮助!谢谢!
<div ng-controller="myCtrl">
<div ng-repeat="(prop, ignoredValue) in wines[0]" ng-init="filter[prop]={}">
<b>{{prop | capitalizeFirst}}:</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>
<hr />
Number of results: {{filtered.length}}
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: "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;
/**/
/*
// Use this snippet for matching with OR
var matchesOR = true;
for (var prop in $scope.filter) {
if (noSubFilter($scope.filter[prop])) continue;
if (!$scope.filter[prop][wine[prop]]) {
matchesOR = false;
} else {
matchesOR = true;
break;
}
}
return matchesOR;
/**/
};
function noSubFilter(subFilterObj) {
for (var key in subFilterObj) {
if (subFilterObj[key]) return false;
}
return true;
}
});
app.filter('capitalizeFirst', function () {
return function (str) {
str = str || '';
return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
};
});
【问题讨论】:
-
filter不支持对对象键进行过滤。 -
我明白了...您认为有什么方法可以轻松解决这个问题吗? @runTarm
-
预期的结果是什么?在你的小提琴中,我无法找出任何问题。
-
我想从对象中排除每个类别:“值”,或者每个名称:“值”。基本上我想这样做,例如,对象包括用户名、id、名字、姓氏等。我想排除某些键,如 id @runTarm
标签: javascript angularjs angularjs-ng-repeat