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

标签 angularjs pagination angular-ui watch 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 .我想要实现的是在应用过滤器时对要排序的整个项目集(而不仅仅是当前分页的项目)进行排序。

为了实现这一点,我想我会在 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/

相关文章:

javascript - 无法选择 ui-select2 创建的列表中的项目

php - Zend 分页器变量

mysql - 使用 MySQL 进行高效分页

angularjs - Angular Google Maps - 自动设置 'center' 和 'zoom' 以适应所有标记

javascript - Angular $watch window.pageYOffset 没有更新?

javascript - 使用工厂 AngularJS 提供处理后的数据

javascript - 动态更改 Angular 指令中的 html 元素

python - 必须使用 WorkoutList 实例作为第一个参数来调用未绑定(bind)方法 get_queryset() (什么也没得到)

javascript - CSS - 在文本中滑动

Angularjs - 从模态更改 location.path