1

The problem I am facing is that I have created a datepicker and I want to set its min date and max date based on the days I gather from a json.

The problem is that by the time the datepicker is initialised the $scope variables are null.

$scope.dates = [];
$scope.stats = {};
$scope.latestDay;
$scope.startDay;

$controller('rightsController', {
    $scope : $scope
});

init();

$("#datepick").datepicker({
    changeMonth: true,
    changeYear: true,
    buttonImageOnly: true,
    dateFormat: 'dd/mm/yy',
    minDate: ''+$scope.startDay,
    maxDate: ''+$scope.latestDay
});

function init() {
    fetchHourlyStats0();
}

$scope.fetchComparativeStats = function() {
    fetchHourlyStats0();
}

function fetchHourlyStats0() {
    var promiseStats = statsFactory.getHourlyStats();
    $q.all([ promiseStats ]).then(function(values) {
       $scope.stats = values[0].data;
       i = 0;
       for ( var k in $scope.stats) {
           $scope.dates[i] = k;
           var v = $scope.stats[k];
           i++;
       }
       var length = $scope.dates.length-1;
       $scope.latestDay = $scope.dates[0];
       $scope.startDay = $scope.dates[length];
    })
}

Is it possible to create the datepicker after the data access object is created and after I fill the variables?

Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
John
  • 11
  • 1

1 Answers1

1

First of all, I really suggest you to stop mixing Jquery and Angular. Have a look at this thread : "Thinking in AngularJS" if I have a jQuery background? I think you will have it really difficult to get the value set by jquery into your picker.

But, this is not your issue right now.

function fetchHourlyStats0() {
    var promiseStats = statsFactory.getHourlyStats();
    $q.all([ promiseStats ]).then(function(values) {
       // code removed
       $scope.latestDay = $scope.dates[0];
       $scope.startDay = $scope.dates[length];

       $("#datepick").datepicker({
            changeMonth: true,
            changeYear: true,
            buttonImageOnly: true,
            dateFormat: 'dd/mm/yy',
            minDate: ''+$scope.startDay,
            maxDate: ''+$scope.latestDay
        });

    });
}

You can simply run your jquery code inside the .then() of your promise to defer the creation of your date picker.

Also, promiseStats looks like a single promise. You don't need to inject $q into your controller. Use directly your first promise :

statsFactory.getHourlyStats().then(function(values){
    //
});

or

var promiseStats = statsFactory.getHourlyStats();
promiseStats.then(function(values){
   //
});
Community
  • 1
  • 1
Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
  • Thank you for your reply! I Will study the link you provided. As for the code, I tried that before, if I put the code there the datepicker has no available min/maxDate. It doesn't allow me to choose any day. – John Jan 13 '16 at 13:32