Angularjs过滤器无法按预期工作

时间:2014-12-30 08:15:50

标签: javascript angularjs

我的代码就像这样

  $scope.AddressData.Address = [
            {
                "LocationId": 66927,
                "ClientId": 114,
                "UserId": 431
            },
            {
                "LocationId": 66928,
                "ClientId": 114,
                "UserId": 431
            },
            {
                "LocationId": 66929,
                "ClientId": 114,
                "UserId": 431
            },
            {
                "LocationId": 66930,
                "ClientId": 114,
                "UserId": 431
            }
        ];
        var found = $filter('filter')($scope.AddressData.Address, { LocationId: '66927' }, true);
        console.log(found);

所有看起来都没问题,但这总是返回一个空数组。谁能指出我做错了什么?

2 个答案:

答案 0 :(得分:2)

angular docs on filter,特别是$filter的最后一个参数:

  

比较器 true:函数的简写(实际,预期){return angular.equals(actual,expected)}。这基本上是对预期和实际的严格比较。

如果您将过滤器更改为:

$filter('filter')($scope.AddressData.Address, { LocationId: '66927' });

或:

$filter('filter')($scope.AddressData.Address, { LocationId: 66927 }, true);

它将按预期工作。

答案 1 :(得分:1)

当传入true时,Angular会在使用过滤器时进行精确的类型检查。而是将locationId用作int:

var found = $filter('filter')($scope.AddressData.Address, { LocationId: 66927 }, true);

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