0

I have 2 input element as follows in my HTML:

<input type="date" ng-model="calendarStart" class="form-control" style="display: inline-block; width: 180px !important;" />
<input type="date" ng-model="calendarEnd" class="form-control" style="display: inline-block; width: 180px !important;" />

and have .js :

$scope.calendarStart = new Date();
$scope.calendarEnd = new Date();
$scope.calendarEnd.setDate($scope.calendarEnd.getDate() + 7);

var firstEndDate = new Date();
var firstStartDate = new Date();

var startData = "calendarStart";
var endData = "calendarEnd";

$scope.changeCalendarStart = function () {           
   dataService.settings_get(startData).then(function(response) {
      firstStartDate = response;
         if (firstStartDate != null) 
            $scope.calendarStart = firstStartDate;

      return firstStartDate;
   });
   return firstStartDate;
};

How I can get response value from .then function , caz need to change value in inputs ?

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
A.Zabelsky
  • 11
  • 1
  • 1
  • 5

1 Answers1

1

You are not understanding promises and their chaining. They are asynchronous, so you can't return a value as "firstStartDate" to their caller, because the caller doesn't know when to grab it.

So, try changing your changeCalendarStart to something like this:

$scope.changeCalendarStart = function () {           
  return $q.function(resolve, reject){
     dataService.settings_get(startData).then(function(response) {
      firstStartDate = response;
         if (firstStartDate != null) 
            $scope.calendarStart = firstStartDate;

      resolve(firstStartDate); //from here, we are going to the then function of the caller below
   });
  }
};

and use it like a promise, e.g. this way:

$scope.changeCalendarStart().then(function(resultValue){ //this inner function it's called by the row with resolve(firstStartDate) above
  $scope.myResultValue = resultValue; 
}

I suggest you to follow a tutorial on promises to fully understand them. This is a good example of it.

illeb
  • 2,942
  • 1
  • 21
  • 35