AngularJS - ngRepeat排序更改数组的长度

时间:2017-12-19 11:33:24

标签: javascript arrays angularjs sorting angularjs-material

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

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

我使用过滤器/排序的组合,包括通过链接到'showLeavers'$ filter指令的复选框选项来过滤/退出员工和完成'leaveDate'属性的选项。

在我的本地副本中,当未选中该复选框并且选择了第二个或第三个排序选项时,阵列将被清除,因此ng-repeat列表中不会显示任何内容,但是当选中该复选框时,或者选择第一个或第四个排序选项,列表显示应该。

显然代码中的某个问题(我猜想过滤器指令),因为我可以像上面的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;
    }
})

1 个答案:

答案 0 :(得分:1)

您需要更改.splice(),您需要提供元素的索引以及要拼接的元素数量:

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

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

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