0

Can someone tell me what I'm doing wrong? I have JSON data that I'm converting to an array for an ng-repeat. Before I iterate through the array, I am comparing the event dates to today's date and splicing the ones that have already passed. However, for some reason, the only thing in the splice getting respected is the 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; }
        });

and a sample of the JSON:

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

1 Answer 1

0

Note: I am assuming that $scope.training is an array, not an object.

The iterator callback for angular.forEach has the following signature: iterator(value, key, obj). When applied to an array, key holds the index of the item in the array: angular.forEach documentation.

That means that you can update your code to make the second argument index instead of date, and in the splice statement, splice by index.

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; }
});
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work. I actually tried a similar approach since angular allows you to access the objects index through the objects array (eg. event.$index) but neither that nor this approach makes any change to the output. BTW, you are correct: I was just showing one object of the array since they are all identical except for the endDate attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.