我有一个对象数组,即过滤和分页,现在我想按不同的对象属性排序列表项。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
寻找在一个阵列的变化在它的长度?如果是的话,什么是最好的方式来实现我想要的。任何帮助,将不胜感激。