最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular filter checks for 'contains' and not 'equals' - Stack Overflow

programmeradmin2浏览0评论

I'm trying to match rules to fields using the 'filter' filter in Angular as shown here:

I'm using the filter as shown below:

<div ng-repeat="f in fields">
      <h4>{{f.id}}</h4>
      <li ng-repeat = "rule in rules | filter:{field: {id: f.id} }">
        {{rule.name}}
      </li>
    </div>

This works fine with single digit ids, but with two digits, as shown below:

$scope.fields = [{id: 1}, {id: 2}, {id: 3}];
$scope.rules = [{name: "A", field: {id: 12, age: 3}}, {name: "B", field: {id: 2, age: 1}}];

The rule with id 12 gets matched to the fields with ids of 1 and 2, when it should only get matched to fields of id 12. Is there a way to do this with the default filter, or should I create a custom filter?

I'm trying to match rules to fields using the 'filter' filter in Angular as shown here: http://plnkr.co/edit/dQiv5lRzhQNjXZ6pVdWO?p=preview

I'm using the filter as shown below:

<div ng-repeat="f in fields">
      <h4>{{f.id}}</h4>
      <li ng-repeat = "rule in rules | filter:{field: {id: f.id} }">
        {{rule.name}}
      </li>
    </div>

This works fine with single digit ids, but with two digits, as shown below:

$scope.fields = [{id: 1}, {id: 2}, {id: 3}];
$scope.rules = [{name: "A", field: {id: 12, age: 3}}, {name: "B", field: {id: 2, age: 1}}];

The rule with id 12 gets matched to the fields with ids of 1 and 2, when it should only get matched to fields of id 12. Is there a way to do this with the default filter, or should I create a custom filter?

Share Improve this question asked Jun 20, 2014 at 18:07 aftrumpetaftrumpet 1,2892 gold badges18 silver badges28 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

I had the same problem and I've found this article that solved the problem Angular JS filter equals

In your case you should write:

<div ng-repeat="f in fields">
      <h4>{{f.id}}</h4>
      <li ng-repeat = "rule in rules | filter:{field: {id: f.id} }:true">
        {{rule.name}}
      </li>
    </div>

You can create your own filter:

.filter('byId',function(){
  return function(items, id){
    var res = [];
    for(var i=0;i<items.length;i++){
      if(items[i].field.id===id){
        res.push(items[i]);
      }  
    }
    return res;
  };
});

Html:

<li ng-repeat = "rule in rules | byId:f.id">
  {{rule.name}}
</li>

http://plnkr.co/edit/d3jmMWOwsHlMEya2Kjei?p=preview

Angular supports Equals match natively. in place of parator function, just pass "true". By default it is false.

In HTML Template Binding

{{ filter_expression | filter : expression : true }}

In JavaScript

$filter('filter')(array, expression, true)

Refer: Angular Js Documentation

发布评论

评论列表(0)

  1. 暂无评论