【问题标题】:AngularJS - ngRepeat sorting changes length of arrayAngularJS - ngRepeat 排序改变数组的长度
【发布时间】:2018-06-01 20:04:57
【问题描述】:

JSFiddle:http://jsfiddle.net/WdVDh/101/.

由于某种原因,当我更改 ng-repeat 列表的排序选项时,数组的长度会发生变化,并且在我的本地副本中,所有项目都会被删除。

我使用了过滤器/排序的组合,包括通过链接到“showLeavers”$filter 指令的复选框选择来过滤具有已完成“leaveDate”属性的员工的选项。

在我的本地副本中,当未选择复选框且选择了第二个或第三个排序选项时,将清除数组,因此在NG-Repeat列表中没有任何内容,但选择复选框时,或者选择第一个或第四个排序选项后,列表将按原样显示。

显然代码中的某个地方存在问题(我猜是 filter 指令),因为我可以在上面的 JSFiddle 中演示类似的东西。


HTML:

<md-list-item ng-repeat="employee in employees | orderBy: sortEmployees | filter: searchEmployees | showLeavers:showLeaver">

<md-input-container class="col-xs-12 col-sm-6 col-md-3">

    <label>Sort by</label>

    <md-select ng-model="allEmployees.sortEmployees">

        <md-option selected value="surname">Surname - A to Z</md-option>

        <md-option value="-surname">Surname - Z to A</md-option>

        <md-option value="forename">Forename - A to Z</md-option>

        <md-option value="-forename">Forename - Z to A</md-option>

    </md-select>

</md-input-container>

<md-checkbox ng-model="showLeaver">Show Leavers?</md-checkbox>

过滤器:

app.filter('showLeavers', function() {
return function (employees, showLeaver) {
    var matches = [];

    angular.forEach(employees, function(value) {
        matches.push(value);

        if (value.leaveDate && !showLeaver) {
            matches.splice(value);
        }
        return matches;
    }
})

【问题讨论】:

    标签: javascript arrays angularjs sorting angularjs-material


    【解决方案1】:

    你需要更改你的.splice(),你需要提供元素的索引,以及你想要拼接多少元素:

    matches.splice(matches.indexOf(value), 1);
    

    或者,您可以像这样使用.filter()

    var matches = employees.filter(match => match.leaveDate.length <= 0 || showLeaver);
    

    【讨论】:

    • 完美,在我的本地版本中用第一行修复了它(使用那个是因为我实际上理解它的作用)
    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2012-07-21
    • 1970-01-01
    相关资源
    最近更新 更多