Angularjs - 在控制器范围内使用orderby过滤器

Amy*_*yth 8 pagination watch angularjs angular-ui 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>
Run Code Online (Sandbox Code Playgroud)

这似乎工作正常,单击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');
});
Run Code Online (Sandbox Code Playgroud)

该sortItems方法工作并更改顺序,但视图中的项目未更新,因为$watch未触发代码.我假设它可能没有被改变,因为它中的数据$scope.filtered没有被改变,只是索引被改变了.所以我在数组的末尾添加了空元素:

$scope.sortItems = function(value) {
    $scope.filtered = $filter('orderBy')($scope.filtered, value);
    $scope.filtered.push({});
};
Run Code Online (Sandbox Code Playgroud)

现在,Everything按预期工作但我不能在数组中保留一个空对象,因为它会影响显示的项目,计数和数据.所以我想我会添加和删除一个空项目.所以改成以上内容:

$scope.sortItems = function(value) {
    $scope.filtered = $filter('orderBy')($scope.filtered, value);
    $scope.filtered.push({});
    $scope.filtered.pop();
};
Run Code Online (Sandbox Code Playgroud)

但是猜猜$watch代码再没有被解雇.

题

我的问题是$watch根据它的长度来查找数组中的变化吗?如果是,那么实现我想要的最好的方法是什么.任何帮助,将不胜感激.

Amy*_*yth 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');
})  
Run Code Online (Sandbox Code Playgroud)