Angular 范围在 orderBy 之后不更新

Angular scope not updating after orderBy

我正在构建一个呈现 table 的 angular 组件,并且我 运行 遇到了排序功能的一些问题。本例中的范围如下所示:

$scope.listState = {
    sortBy: '<string>',
    sortReverse: <bool>,
    headings: {...},
    list: [
        {
            rowCols: {
                user: 'timfranks@gmail.com',
                name: 'Tim Franks',
                since: '11/6/12'
            }
            rowState: {...}
        },
        {
            {
                user: 'albertjohns@sbcglobal.net',
                name: 'Alber Johns',
                since: '11/12/13'
            },
            rowState: {...}
        },
        {
            {
                user: 'johnsmith@sine.com',
                name: 'John Smith',
                since: '7/28/14'
            },
            rowState: {...}
        }
    ]
};

我最初尝试通过以下方式对列表进行排序:

ng-repeat="row in $ctrl.list | orderBy:$ctrl.listState.sortBy:$ctrl.listState.sortReverse"

这没有用,尽管在使用调试器进行跟踪时我发现 orderBy 实际上获得了正确的参数并返回了正确排序的列表。为了确定,我更改了代码以在我的控制器中使用 orderBy,如下所示:

this.listState.list = _this.orderBy(listState.list, 'rowCols.' +  listState.sortBy, listState.sortReverse);

这是第一次工作(在构造函数中调用),但随后停止工作。我很确定这是 Angular 范围的某些方面我不完全理解。任何帮助将不胜感激。

ng-repeat 表达式中使用过滤器 不会更新原始模型,而是创建数组的副本。

你在 this.listState.list = _this.orderBy(...) 的正确轨道上......它只被调用一次确实有意义。

如果 listState.list 模型在控制器加载后获得新值并且您想使用这些新值,您可能想使用类似的东西:

$scope.$watchCollection('listState.list', function listChanged(newList, oldList){
    $scope.listState.list = _this.orderBy(...);
});

我不记得 $watchCollection 是否会在顺序更改时注册更改,但是如果您最终陷入该代码的无限循环,您可以放置​​一个阻止程序,例如:

var listSorting = false;
$scope.$watchCollection('listState.list', function listChanged(newList, oldList){
    if(!listSorting){
        listSorting = true;
        $scope.listState.list = _this.orderBy(...);
        $timeout(function resetSortBlock(){ // try it without the $timeout to see if it will work
            listSorting = false;
        });
    }
});

想通了。问题是我使用了属性指令来呈现列表行,并且属性指令和 ng-repeat 在同一个元素上。这在两个指令之间造成了范围冲突。我将我的指令移动到 ng-repeat 中的 div 并且它工作正常。