Vishal Vishal - 4 months ago 11
AngularJS Question

How to store dates in json format and display them one by one for a given range?

I am new to angularjs and I am trying to store dates in a json format and display it in a list wise manner.

Here,I want the minDate to be the date which the user gives and the maxDate to be the current date.

I want to display dates from the minDate to maxDate through a 'for' loop in which dates are incremented by 1,do we need a function to calculate the no. of days also?




HTML

<div ng-app='myApp' ng-controller="Main">
<input type="date" ng-model="min">
<li ng-repeat="n in range(min,max)">{{dt.date | date}}</li>
</div>


Controller

myApp.controller('Main', function ($scope){
$scope.max = new Date();
$scope.date = [];
$scope.range = function(min, max){
for (var i = min; i <= max; i ++) {
date.setDate(date.getDate() + i);
$scope.date.push({
dt: $scope.date
});
return date;
}
};





Output should be like

Date 1:
07/20/2016
Date 2:
07/24/2016

Day difference = n
Day 1=20 July.2016

Day 2=21 July.2016

Day 3=22 July.2016

Day 4=23 July.2016

Day 5=24 July.2016

Answer

I would not use a function in ng-repeat because it will be called with each digest cycle. Instead, only call the function when your min date has changed. So here's how it would look:

Controller

myApp.controller('Main', function($scope) {
  $scope.min = new Date();
  $scope.max = new Date();
  $scope.dateRange = [];

  $scope.getDateRange = function() {
    $scope.dateRange = [{
      dt: angular.copy($scope.min)
    }];

    for (var thisDate = $scope.min; thisDate < $scope.max;) {
      thisDate.setDate(thisDate.getDate() + 1);

      $scope.dateRange.push({
        dt: angular.copy(thisDate)
      });
    }
  };
});

HTML

<div ng-controller="Main">
  <input type="date" ng-model="min" ng-change="getDateRange()">
  <li ng-repeat="d in dateRange">{{ d.dt | date}}</li>
</div>

You can see it working here