我有一个对象数组,即过滤和分页,现在我想按不同的对象属性对列表项进行排序。
我试过 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
.我想要实现的是在应用过滤器时对要排序的整个项目集(而不仅仅是当前分页的项目)进行排序。为了实现这一点,我想我会在 Controller 范围内使用一种方法。所以我把上面的改成了:
/** 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
方法有效并更改顺序,但 View 中的项目不会更新为 $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
根据数组的长度查找数组的变化?如果是,那么实现我想要实现的目标的最佳方法是什么。任何帮助,将不胜感激。
最佳答案
好的,我使用 $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');
})
关于Angularjs - 在 Controller 范围内使用 orderby 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20632060/