【问题标题】:Filter array of objects by attribute with integer value in ng-repeat在 ng-repeat 中按具有整数值的属性过滤对象数组
【发布时间】:2015-07-03 04:21:06
【问题描述】:

我有这样的指令

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” - 它完全清除输出(结果数组),它适用于简单的字符串数组,但不适用于对象(“t​​rue”希望与模式对象完全匹配,这意味着它的所有属性)

解决了!!!

对不起各位,是我的错! 'inputID' 与 'id' (字符串与整数)不是同一类型,因此内置比较器 (":true") 返回 false。非常感谢!

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

【问题讨论】:

  • 所以您想要完全匹配?看看这个stackoverflow.com/questions/17480526/…
  • 我尝试在过滤器表达式中添加 ":true" - 它完全清除输出(结果数组),它适用于简单的字符串数组,而不是对象("true" 需要完全匹配与模式对象,这意味着具有所有属性)

标签: arrays angularjs angularjs-ng-repeat angularjs-filter


【解决方案1】:

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

你能不能把代码改成:

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

【讨论】:

  • 我尝试在过滤器表达式中添加“:true” - 它完全清除输出(结果数组),它适用于简单的字符串数组,而不是对象(“t​​rue”比较所有属性)
  • 这不起作用,因为 angular.equals 不匹配,因为类型不匹配
【解决方案2】:

您需要提供自己的比较器或手动将查询到的值转换为整数并使用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

【讨论】:

    【解决方案3】:

    编写您自己的比较器。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-19
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多