繁体   English   中英

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

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

每当过滤的集合发生更改时,我都试图触发事件。 过滤列表附加到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.filtered,但不是。

我也尝试过使$ 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过滤器上的begin选项不再起作用。 更改限制选项仍然有效,但不是开始。 更改begin仍然可以与$ 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM