我有一个产品数组,我在使用ng-repeat和正在使用
<div ng-repeat="product in products | filter:by_colour">
按颜色过滤这些产品。滤镜正在工作,但如果产品名称/描述等包含颜色,那么在滤镜应用后,产品仍然存在。
我如何设置过滤器只适用于我的数组的颜色字段,而不是每个字段?
我有一个产品数组,我在使用ng-repeat和正在使用
<div ng-repeat="product in products | filter:by_colour">
按颜色过滤这些产品。滤镜正在工作,但如果产品名称/描述等包含颜色,那么在滤镜应用后,产品仍然存在。
我如何设置过滤器只适用于我的数组的颜色字段,而不是每个字段?
当前回答
如果希望筛选给定对象的孙辈(或更深层),则可以继续构建对象层次结构。例如,如果你想过滤'thing.properties. properties '。Title ',您可以执行以下操作:
<div ng-repeat="thing in things | filter: { properties: { title: title_filter } }">
你也可以过滤一个对象的多个属性,只需将它们添加到你的过滤器对象:
<div ng-repeat="thing in things | filter: { properties: { title: title_filter, id: id_filter } }">
其他回答
你可以通过一个对象来过滤,它的属性与你要过滤的对象相匹配:
app.controller('FooCtrl', function($scope) {
$scope.products = [
{ id: 1, name: 'test', color: 'red' },
{ id: 2, name: 'bob', color: 'blue' }
/*... etc... */
];
});
<div ng-repeat="product in products | filter: { color: 'red' }">
这当然可以通过变量传递,正如Mark Rajcok建议的那样。
小心使用角滤镜。如果你想在字段中选择特定的值,你不能使用过滤器。
例子:
javascript
app.controller('FooCtrl', function($scope) {
$scope.products = [
{ id: 1, name: 'test', color: 'lightblue' },
{ id: 2, name: 'bob', color: 'blue' }
/*... etc... */
];
});
html
<div ng-repeat="product in products | filter: { color: 'blue' }">
这将选择两者,因为使用类似substr的东西,这意味着你想选择产品,其中“颜色”包含字符串“蓝色”,而不是“颜色”是“蓝色”。
按颜色搜索:
<input type="text" ng-model="searchinput">
<div ng-repeat="product in products | filter:{color:searchinput}">
你也可以做一个内巢。
filter:{prop1:{innerprop1:searchinput}}
在filter中指定要应用筛选器的对象的属性:
//Suppose Object
var users = [{
"firstname": "XYZ",
"lastname": "ABC",
"Address": "HOUSE NO-1, Example Street, Example Town"
},
{
"firstname": "QWE",
"lastname": "YUIKJH",
"Address": "HOUSE NO-11, Example Street1, Example Town1"
}]
但是你想只对名字应用过滤器
<input type = "text" ng-model = "first_name_model"/>
<div ng-repeat="user in users| filter:{ firstname: first_name_model}">
如果你想过滤一个字段:
label>Any: <input ng-model="search.color"></label> <br>
<tr ng-repeat="friendObj in friends | filter:search:strict">
如果你想过滤所有字段:
label>Any: <input ng-model="search.$"></label> <br>
<tr ng-repeat="friendObj in friends | filter:search:strict">
而且 https://docs.angularjs.org/api/ng/filter/filter对你有好处