Angular数组没有正确拼接(纯JS)

时间:2017-02-03 16:45:30

标签: javascript angularjs angularjs-ng-repeat

有人可以告诉我我做错了什么吗?我有JSON数据,我正在转换为数组进行ng-repeat。在迭代数组之前,我将事件日期与今天的日期进行比较并拼接已经过去的日期。但是,出于某种原因,剪辑中唯一受到尊重的是deleteCount。

    angular.forEach($scope.training, function(event, date) {
        var d = event.endDate;
        var evDate = d.toString();
        console.log(evDate);
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();
        if(dd<10) {
            dd='0'+dd;
        } 
        if(mm<10) {
            mm='0'+mm;
        } 
        today = mm+'/'+dd+'/'+yyyy;
        console.log(today);
        var d1 = Date.parse(evDate);
        var d2 = Date.parse(today);
        console.log(d1+','+d2);
        if (d1 <= d2) {
            $scope.training.splice(event,1);
        } else { return false; }
        });

和JSON的样本:

    {"name": "Name","date": "Jan 18","location": "Houston, TX","endDate": "01/19/2016"}

1 个答案:

答案 0 :(得分:0)

注意:我假设$scope.training是一个数组,而不是一个对象。

angular.forEach的迭代器回调具有以下签名:iterator(value, key, obj)。应用于数组时,key保存数组中项目的索引:angular.forEach documentation

这意味着您可以更新代码以使第二个参数index而不是日期,并且在splice语句中,按索引进行拼接。

angular.forEach($scope.training, function(event, index) {
    var d = event.endDate;
    var evDate = d.toString();
    console.log(evDate);
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10) {
        dd='0'+dd;
    } 
    if(mm<10) {
        mm='0'+mm;
    } 
    today = mm+'/'+dd+'/'+yyyy;
    console.log(today);
    var d1 = Date.parse(evDate);
    var d2 = Date.parse(today);
    console.log(d1+','+d2);
    if (d1 <= d2) {
        $scope.training.splice(index,1);
    } else { return false; }
});