Getting value per Angular Foeach loop


#1

Hi All,

I need to get the value every foreach loop in Angular? Is this possible?

angular.forEach($scope.Reports, function(report) {
   var _dateString = report.date + ", " + report.time;
   console.log("_dateString: "+_dateString);

   $scope.newDate = new Date(_dateString).getTime();
   console.log("NEW DATE: "+$scope.newDate);             
});

I am trying to loop from a Scope that contains a JSON Data. Every loop I get a date and time values and parse it Date Format. I need to get the values ($scope.newDate) processed every loop.

Help please.

Thank you.


#2

extend a report with the correct date format:

angular.forEach($scope.Reports, function(report) {
 var _dateString = report.date + ", " + report.time;
 console.log("_dateString: "+_dateString);

 report.formattedDate = new Date(_dateString).getTime();
 console.log("NEW DATE: "+report.formattedDate);             
});

so you can loop over your reports in the template and get the date.
or you build up a new array in that loop.

Consider that angular.forEach is a very slow looping functionality. If you have many datasets you should use basic javascript for-loop.
Another performance hint:
Do not change $scope-values directly in a loop. every time you change something and the $digest is called the values are changed or checked for changes. Try to build up your final datastructure and then put it on the scope. By the way the definition of variables in a loop is also not the best approach. Declare it outside. So you reuse the same reference.
So you get something like that:

var reports = [{date: ..., time: ...}, {date: ..., time: ...}],
     _dateString,
     i = 0;

for (i; i < reports.length; i = i + 1) {
    _dateString = report.date + ", " + report.time;
    reports.parsedDate = new Date(_dateString).getTime();
}

$scope.reports = reports;

#3

Hi @bengtler,

My issue here is how can I extract the data and time values from the $scope.reports at the same time I process/parse it to date string?

I appreciate your tips. Thank you :smile: