我有一个对象数组,即过滤和分页,现在我想按不同的对象属性对列表项进行排序。
我尝试了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
根据数组的长度查找数组的变化?如果是,那么实现我想要实现的目标的最佳方法是什么。任何帮助,将不胜感激。