如何在 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.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);
相关文章:
- 过滤Meteor集合
- Meteor-以模板级别订阅过滤集合
- 如何过滤/修改主干集合本身,而不是获取新数组
- 主干.js中的过滤模型(不是集合)
- 在返回 1 结果时过滤主干集合
- 如何在 Angular.JS 中观看过滤后的集合
- 过滤后如何使用原始Backbone集合
- Backbone.js-过滤集合与多个集合
- 过滤集合上的Angular watch侦听器在错误的时间调用
- 使用Knockback.js过滤中的视图模型集合
- 已发布集合的Meteor反应过滤
- backbone.js使用子字符串过滤集合
- 使用来自输入的值过滤集合
- 我应该使用什么来过滤服务器上的backbonejs集合
- 骨干过滤使用多个属性的集合
- js查询模型通过集合属性过滤
- 如何在使用AngularJS ng-repeat时访问过滤对象集合?
- ng-repeat绑定集合,使用选项卡过滤布尔值,当我更新集合时,过滤器不会重新应用
- 过滤多个模型属性上的主干集合
- 骨干.渲染/重置过滤集合