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

时间:2016-01-16 18:56:51

标签: javascript angularjs

每当更改过滤后的集合时,我都会尝试触发事件。已过滤的列表将附加到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);
        });

但结果相同。

我也尝试按照建议here进行操作,结果如下:

<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选项不再有效。更改限制选项仍然有效,但不是开始。改变开始仍然可以使用$ watchCollection方法。

有没有人有任何想法?

2 个答案:

答案 0 :(得分:1)

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

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

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

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

&#13;
&#13;
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);
  })
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

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