2016-01-16 58 views
1

我試圖在過濾的集合發生更改時發生事件觸發。已過濾的列表以ng-repeat附加到未過濾的列表。如何在Angular.JS中觀看已過濾的集合?

<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方法。

有沒有人有任何想法?

+0

太開始的手錶,你需要消化()因爲你正在使用警報,你必須調用apply()方法手動這將導致digest()運行,因此你的觀察者。 –

+2

@AayushiJain請引用文檔。從未在手錶中使用'$ apply()'或'$ digest()'來處理角度範圍內的任何事情 – charlietfl

+0

'$ scope.filtered'中的項目無效......視圖中沒有'$ scope' ...在vm.filtered =(....)中是'item並且在使用'controllerAs'時需要使用函數 – charlietfl

回答

1

當您在視圖中創建一些變量時,它將作爲屬性添加到當前範圍。所以,你的情況你創建$scope.filtered,並將其添加到當前範圍。
爲了得到它的手錶,你只需要使用相同的聲明

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

但最好不要用變量名狀$範圍,以免它們與角變量混淆。

所以,你可以改變它ロ簡單:過濾

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>

+0

我剛剛使用$ scope,並且我讀的文檔聽起來像只有在控制器中聲明的變量,因爲可以監視$ scope的屬性。顯然這完全不是真的。所以我評論了$ scope.filtered = []的聲明;並將我的ng-repeat改爲:。然後它完美地工作。非常感謝。 – SurgeBinder

+0

@SurgeBinder,你可以看到任何'$ scope'字段,無論何時何地聲明,也可以將函數作爲'watchExpression'參數傳遞,所以你不僅可以觀察$ scope字段。請參閱[文檔和示例](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch) – Grundy

0

您將希望使用函數來返回過濾列表並將對象相等設置爲true。

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