gpt4 book ai didi

javascript - 我如何在 Angular.JS 中查看过滤后的集合?

转载 作者:行者123 更新时间:2023-11-30 16:20:28 24 4
gpt4 key购买 nike

我试图在过滤的集合发生更改时触发事件。过滤列表附加到 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 过滤器上的开始选项不再有效。更改限制选项仍然有效,但不是开始。更改开始仍然适用于 $watchCollection 方法。

有没有人有什么想法?

最佳答案

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

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

但最好不要使用像$scope 这样的变量名,以免与 Angular 变量混淆。

因此,您可以将其更改为简单的:过滤

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>

关于javascript - 我如何在 Angular.JS 中查看过滤后的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34830854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com