如何在AngularJS中使用嵌套对象按对象搜索

时间:2015-11-19 13:27:02

标签: javascript html angularjs

我想通过搜索对象过滤我的订单集合。想在视图中仅显示匹配的订单。

我有订单数组集合,如:

$scope.orders = [{ 
    "_id" : "56461e2b7caaf49345076709", 
    "customer" : {"_id": "76461e2b7caaf49345076a19b", "name": "cr1"},
    "seller" : {"_id": "96461e2b7caaf49345076a18b", "name": "sl1"}, 
    "address" : "Squire Park",
    "qt" : 5
},
{ 
    "_id" : "56461e2b7caaf49345076708", 
    "customer" : {"_id": "76461e2b7caaf49345076a19b1", "name": "cr2"},
    "seller" : {"_id": "96461e2b7caaf49345076a18c1", "name": "sl2"}, 
    "address" : "Squire Park1", 
    "qt" : 6
},
..................
];

和我的搜索对象如:

$scope.search = {
    "qt": 5,
    "customer" : {"_id": "76461e2b7caaf49345076a19b1"},
    "seller" : {"_id": "96461e2b7caaf49345076a18c1"}
};

视图:

<tr data-ng-repeat="order in orders | myFilter:search">
      <td>{{order._id}}</td>
      <td>{{order.customer.name}}</td>
</tr>

我的 myFilter 功能应该是什么?

谢谢你。

1 个答案:

答案 0 :(得分:0)

一个相当简单的解决方案是将过滤函数附加到范围

$scope.orderFilter = function(order) {
  // implementation depends on how you want the search to behave
  // for example, if the order should match every property of the searchObj
  var pass = true;
  for (var property in $scope.search) {
    if ($scope.search.hasOwnProperty(property)) {
      if($scope.search[property] != order[property]) {
        pass = false;
      }
    }
  }
  return pass;
  // .. though i wouldnt recommend this implementation
  // you´d be better off by implementing a more specific matching
}

在视图中

<tr data-ng-repeat="order in orders | filter:orderFilter">
  <td>{{order._id}}</td>
  <td>{{order.customer.name}}</td>
</tr>

如果您希望使用过滤器表达式,则必须在模块上注册自定义过滤器。这将是这样做的:

angular.module('app').filter('myFilter', function() {
  return function(orders, searchObj) {
    var filteredOrders = [];
    orders.forEach(function(order) {
      // evaluate if you want to have the order show up based on the searchOjb
      // .. if so, add it to the array like so:
      filteredOrders.push(order);
    });
    return filteredOrders;
  }
});

注意

如果更改搜索对象的属性,则不会再次调用过滤器函数,因为角度过滤器不会侦听嵌套属性的更改。只有在更改整个搜索对象时才会调用过滤器。