for循环在迭代多个值时不返回数据

时间:2017-10-02 21:02:29

标签: javascript angularjs

我有一个函数,它的工作是删除用户选择的值,它遍历所选值和数据的数组,当它遍历时它检查所选值是否等于所有值中的任何属性数据,如果它返回true,我得到一个新的数据数组。

当我在复选框中选择一个值时,我确实看到返回了正确的数据,但是当我选择多个时,我的功能不起作用。我整天都在思考,我真的很感激任何意见。

HTML

<div class="ibox-content">
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Select</th>
                <th class="col-xs-3">Issue Description</th>
                <th class="col-xs-3 text-center">Category</th>
                <th class="col-xs-3 text-center">Jira</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="issue in wiq.data">
                <td><input type="checkbox" checklist-model="wiq.selections" checklist-value="issue.jira"> </td>
                <td>{{issue.issue}}</td>
                <td class="text-center">{{issue.description}}</td>
                <td class="text-center">{{issue.jira}}</td>
            </tr>

            <pre>{{wiq.selections}}</pre>
        </tbody>
    </table>
    <form>
        <button type="button" name="button" class="btn btn-success pull-right" style="margin-top:2em;" ng-click="wiq.acknowledge()">Acknowledge</button>
    </form>
</div>

Controller.js

ctrl.selections = []
ctrl.data = [
    {issue:"CMDY has issue", description:"issue",jira:"CDVR-173"},
    {issue:"SPK has issue", description:"issue",jira:"CDVR-125"}
]

ctrl.acknowledge = function() {
    var data = [];
    for (var i = 0; i < ctrl.data.length; i++) {
        for (var j = 0; j < ctrl.selections.length; j++) {
            if (ctrl.selections[j] != ctrl.data[i].jira) {
                data.push(ctrl.data[i]);
            }
        }
    }
    ctrl.data = data;
    console.log(ctrl.data)
};

2 个答案:

答案 0 :(得分:1)

如果您有多个选择,则循环多次,因此您可以调用&#34; push&#34;太多次了。

尝试:

function filterData(somedata, selections) {
    return somedata.filter(item => (selections.findIndex(o => o === item.jira ) == -1));
};

然后

ctrl.acknowledge = function() {
    ctrl.data = filterData(ctrl.data,ctrl.selections);
    console.log(ctrl.data)
};

答案 1 :(得分:0)

简单的一个班轮将解决您的问题,试试这个:

ctrl.acknowledge = function() {
    var data = ctrl.data.filter(val => ctrl.selections.indexOf(val.jira) === -1);
    ctrl.data = data;
    console.log(ctrl.data)
  };

这里的jsfiddle: http://jsfiddle.net/pegla/xj9gqqxn/7/