2013-12-17 68 views
8

我有一個對象數組,即過濾和分頁,現在我想按不同的對象屬性排序列表項。Angularjs - 在控制器的範圍內使用orderby過濾器

我試過orderBy過濾如下:

<th><a href='' ng-click="reverse = sortParam == 'title' && !reverse; sortParam = 'title'">Title</a></th> 

<tr ng-repeat="item in pagedItems|filter:filterParam|orderBy:sortParam:reverse"> 
    <td>{{ item.title }}</td> 
</tr> 

這似乎是做工精細,點擊Title鏈接,按字母順序號令行或根據當前的情況相反的字母順序。

但是,這裏的問題是,只有pagedItems正在訂購,這是有道理的,因爲我們正在將orderBy過濾器應用到pagedItems。我想要實現的是在應用過濾器時對整個項目集合(不僅僅是當前分頁項目)進行排序。

爲了達到這個我想我會在控制器範圍內使用一個方法。所以我改變了上面:

/** In the Template */ 

<th><a href='' ng-click="sortItems('title')">Title</a></th> 

<tr ng-repeat="item in pagedItems|filter:filterParam"> 
    <td>{{ item.title }}</td> 
</tr> 


/** In the Controller */ 

$scope.sortItems = function(value) { 
    $scope.filtered = $filter('orderBy')($scope.filtered, value); 
}; 

$scope.$watch('currentPage + numPerPage + filtered', function() { 
    $scope.pagedItems = getPagedItems($scope, 'filtered'); 
}); 

sortItems方法作品和改變順序,但在視圖中的項目,如$watch代碼將不會觸發沒有更新。我認爲它可能沒有被更改,因爲$scope.filtered中的數據沒有被更改,只是索引正在更改。所以我添加和空元素的數組的末尾:

$scope.sortItems = function(value) { 
    $scope.filtered = $filter('orderBy')($scope.filtered, value); 
    $scope.filtered.push({}); 
}; 

現在,一切都按預期工作,但我不能讓一個空對象數組中,因爲它影響的項目,數量和所顯示的數據。所以我想我會添加和刪除一個空的項目。所以改變了上面:

$scope.sortItems = function(value) { 
    $scope.filtered = $filter('orderBy')($scope.filtered, value); 
    $scope.filtered.push({}); 
    $scope.filtered.pop(); 
}; 

,但猜測$watch代碼不被再次發射。

問題

我的問題是沒有根據$watch尋找在一個陣列的變化在它的長度?如果是的話,什麼是最好的方式來實現我想要的。任何幫助,將不勝感激。

回答

5

好,我解決了這個用$broadcast$on如下:

$scope.sortList = function(value) { 

    if (value === $scope.currentFilter) { 
     value = value.indexOf('-') === 0 ? value.replace("-","") : "-" + value; 
    } 

    $scope.currentFilter = value; 
    $scope.filtered = $filter('orderBy')($scope.filtered, value); 
    $scope.$broadcast('sorted'); 
} 

$scope.$on('sorted', function() { 
    $scope.pagedCandidates = getPagedItems($scope, 'filtered'); 
}) 
相關問題