如何在 Angular.JS 中观看过滤后的集合

How can I watch a filtered collection in Angular.JS?

本文关键字:过滤 集合 中观 Angular JS      更新时间:2023-09-26

每当更改过滤的集合时,我都会尝试触发事件。 过滤后的列表以 ng-repeat 的形式附加到未过滤的列表。

<tr ng-repeat="item in $scope.filtered = (vm.list | filter:vm.searchText) | limitTo:vm.limit:vm.begin">

这是我想要触发的事件:

 $scope.$watchCollection('filtered', function () {
            alert($scope.filtered.length);
        }, true);

它在我的 ajax 调用填充 vm.list 之前首次加载页面时触发一次,因此警报显示 0,但在填充 vm.list 后它应该再次触发,并且每次对 vm.searchText 的更改都会导致对 $scope.filter 的更改,但事实并非如此。

我还尝试像这样制作$watchCollection方法:

$scope.$watchCollection('filtered', function (newList, oldList) {
            alert(newList.length);
        });

但这也有同样的结果。

我也尝试按照这里的建议去做,结果是这样的:

<tr ng-repeat="item in catchData((vm.list | filter:vm.searchText)) | limitTo:vm.limit:vm.begin">
$scope.catchData = function (filteredData) {
            alert(filteredData.length);
            return filteredData;
  }

起初似乎它修复了它。 现在,当 API 调用填充列表时触发,并在 searchText 导致筛选列表更改时再次触发。 不幸的是,它使它如此更改limitTo过滤器上的开始选项不再有效。 更改限制选项仍然有效,但不是开始。 更改开头仍然适用于$watchCollection方法。

有人有什么想法吗?

当您在视图中创建一些变量时,它会作为属性添加到当前范围。因此,在您的情况下,您创建了 $scope.filtered ,这已添加到当前范围。
要让它在手表中,你只需要使用相同的声明

$scope.$watchCollection('$scope.filtered', function () {
    console.log($scope.$scope.filtered.length)
}

但最好不要使用像$scope这样的变量名,以免将它们与角度变量混淆。

所以,你可以简单地改变它:过滤

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.$watchCollection('$scope.filtered', function(nval) {
      if(!nval) return; //nval - new value for watched variable
      console.log('as $scope.filtered in view', $scope.$scope.filtered.length);
    }, true);
    $scope.$watchCollection('filtered', function(nval) {
      if(!nval) return; //nval - new value for watched variable
      console.log('as filtered in view', $scope.filtered.length);
    }, true);
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <input type="text" data-ng-model="search" />
  <h3>as $scope.filtered</h3>
  <div ng-repeat="item in $scope.filtered = ([11,12,23]| filter:search)">item_{{item}} from {{$scope.filtered}}</div>
  <h3>as filtered</h3>
  <div ng-repeat="item in filtered = ([11,12,23]| filter:search)">item_{{item}} from {{filtered}}</div>
</div>

您将

需要使用函数返回过滤列表并将对象相等性设置为 true。

$scope.$watch(function () {
  return $scope.filtered;
}, function (newList) {
  alert(newList.length);
}, true);