【问题标题】:Angular scope not updating after orderByorderBy 后角度范围未更新
【发布时间】:2016-09-09 14:56:09
【问题描述】:

我正在构建一个呈现表格的角度组件,但我遇到了排序功能的一些问题。本例中的作用域如下所示:

$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 范围的某些方面。任何帮助将不胜感激。

【问题讨论】:

  • 抱歉,您能具体说明一下您想要完成的工作吗?

标签: javascript angularjs angularjs-scope angularjs-orderby


【解决方案1】:

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 创建了自己的范围,这帮助我解决了问题。谢谢!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2015-12-14
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    相关资源
    最近更新 更多