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


i'm trying make event fire whenever filtered collection changed. filtered list attached non-filtered list in ng-repeat.

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

and here's event want fire:

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

it fires once when page first loads, before ajax call populates vm.list, alert says 0, should fire again after vm.list gets populated, , every time change vm.searchtext causes change $scope.filtered, it's not.

i tried making $watchcollection method this:

$scope.$watchcollection('filtered', function (newlist, oldlist) {             alert(newlist.length);         }); 

but had same result.

i tried doing suggested here, , ended this:

<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;   } 

that seemed fixed @ first. fired when api call populated list, , fired again whenever searchtext caused filtered list change. unfortunately made changing begin option on limitto filter no longer worked. changing limit option still worked, not begin. changing begin still work $watchcollection method.

does have ideas?

when create variables in view, added property current scope. so, in case create $scope.filtered, , added current scope.
in watch, need use same declaration

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

but better not use variable name $scope, not confuse them angular variables.

so, can change ro simple: filtered

angular.module('app', [])    .controller('ctrl', function($scope) {      $scope.$watchcollection('$scope.filtered', function(nval) {        if(!nval) return; //nval - new value 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 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}} {{$scope.filtered}}</div>    <h3>as filtered</h3>    <div ng-repeat="item in filtered = ([11,12,23]| filter:search)">item_{{item}} {{filtered}}</div>  </div>


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -