我有一个产品数组,我在使用ng-repeat和正在使用

<div ng-repeat="product in products | filter:by_colour"> 

按颜色过滤这些产品。滤镜正在工作,但如果产品名称/描述等包含颜色,那么在滤镜应用后,产品仍然存在。

我如何设置过滤器只适用于我的数组的颜色字段,而不是每个字段?


当前回答

在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}">

其他回答

你可以通过一个对象来过滤,它的属性与你要过滤的对象相匹配:

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建议的那样。

如果你要做以下事情:

<li class="active-item" ng-repeat="item in mc.pageData.items | filter: { itemTypeId: 2, itemStatus: 1 } | orderBy : 'listIndex'"
                id="{{item.id}}">
    <span class="item-title">{{preference.itemTitle}}</span>
</li>

...您不仅可以获得itemTypeId 2和itemStatus 1的项,还可以获得itemType 20、22、202、123和itemStatus 10、11、101、123的项。这是因为过滤器:{…}语法的工作原理类似于字符串包含查询。

然而,如果你要添加:true条件,它将通过精确匹配进行过滤:

<li class="active-item" ng-repeat="item in mc.pageData.items | filter: { itemTypeId: 2, itemStatus: 1 } : true | orderBy : 'listIndex'"
                id="{{item.id}}">
    <span class="item-title">{{preference.itemTitle}}</span>
</li>

指定你想要应用滤镜的属性(即颜色):

<div ng-repeat="product in products | filter:{ colour: by_colour }">

小心使用角滤镜。如果你想在字段中选择特定的值,你不能使用过滤器。

例子:

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的东西,这意味着你想选择产品,其中“颜色”包含字符串“蓝色”,而不是“颜色”是“蓝色”。

你必须使用 过滤器:{color_name:by_colour}代替

filter:by_colour

如果你想匹配一个对象的单个属性,那么写这个属性而不是object,否则其他的属性会被匹配。