首页 文章

按属性过滤对象数组,在ng-repeat中使用整数值

提问于
浏览
7

我有这样的指令

ng-repeat="place in tb_places | filter:{'id':inputID}"

输出一些对象数组看起来像这样

$scope.tb_places = [
{name: 'some1', id:1}
...
{name: 'some10', id:10}
{name: 'some11', id:11}
{name: 'some12', id:12} 
...
]

当我更改inputID并将其设置为1时,结果数组将填充源数组的元素,其中'ids'为1和10,11,12 . 因此,'id'值的部分被检查为子串,而不是数字 . 我该怎样治愈它?

谢谢!

UPD我试图在过滤器表达式中添加“:true” - 它完全清除输出(结果数组),它适用于一个简单的字符串数组,但不适用于对象(“true”想要与模式对象完全匹配,这意味着及其所有属性)

解决了!!!

对不起伙计们,我的错! 'inputID'与'id'(string vs int)的类型不同,因此内置比较器(“:true”)返回false . 非常感谢!

抱歉,我不能为你投票答案 - 缺乏声誉......见到你!

3 回答

  • 6

    您需要根据角度filter添加 comparator 以满足您的要求 .

    您可以将代码更改为:

    ng-repeat="place in tb_places | filter: {'id' : inputID} : true"
    
  • 1

    您需要提供自己的比较器或手动将查询的值转换为整数并使用 true 标志:

    控制器:

    app.controller('DemoCtrl', function() {
      this.query = '1';
    
      this.queryAsInt = function() {
        return parseInt(this.query, 10);
      };
    
      this.stuff = [
        {id: 1, label: 'Foobar 1'},
        {id: 2, label: 'Foobar 2'},
        {id: 3, label: 'Foobar 3'},
        {id: 4, label: 'Foobar 4'},
        {id: 5, label: 'Foobar 5'},
        {id: 6, label: 'Foobar 6'},
        {id: 7, label: 'Foobar 7'},
        {id: 8, label: 'Foobar 8'},
        {id: 9, label: 'Foobar 9'},
        {id: 10, label: 'Foobar 10'},
        {id: 11, label: 'Foobar 11'},
        {id: 11, label: 'Foobar 12'}
      ];
    
      this.compare = function(a, b) {
        return parseInt(a, 10) === parseInt(b, 10);
      };
    });
    

    视图:

    <div ng-controller="DemoCtrl as demo">
      <input ng-model="demo.query">
      <p>With custom comparator:</p>
      <ul>
        <li ng-repeat="item in demo.stuff | filter:{id:demo.query}:demo.compare">
          {{item.label}}
        </li>
      </ul>
    
      <p>With type casting:</p>
      <ul>
        <li ng-repeat="item in demo.stuff | filter:{id:demo.queryAsInt()}:true">
          {{item.label}}
        </li>
      </ul>
    </div>);
    

    这是一个运行的例子:http://jsbin.com/kecihexeyu/1/edit?html,js,output

  • 1

    编写自己的比较器 .

    HTML

    <li ng-repeat="place in tb_places | filter:{'id':inputID}: filterId">{{place.id}}</li>
    

    使用Javascript

    filterId = function(actual, expected) {
        return actual == expected;
    }
    

    Plunker完整版 . http://plnkr.co/edit/3JEvThiemq8ro8cXCYBd?p=preview

相关问题