Robert Vliek Robert Vliek - 2 months ago 12
AngularJS Question

Angular UI Datepicker json set date not working

I have an angular-ui datepicker, but when I load the date remotely from the json, the datepicker doesn't select the date, but when I type it it does select the date. But it doesn't show in the input its a blank input, and when I click to open the datepicker the correct date is selected.

I would like to have the date loaded in remotely and shown in the datepicker and input field of the datepicker.

This is my code for the datepicker:

<input type="text" class="form-control" uib-datepicker-popup ng-model="dt" ng-click="open()" ng-change="testFun(dt)" is-open="popup.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open()"><i class="glyphicon glyphicon-calendar"></i></button>

Code to set the date:

$ = function() {
$scope.dt = moment($scope.tenderDate, "YYYY-MM-DD").format();

$scope.tenderDate is the following:

$scope.tenderDate = $;

Which is this in the json


The $scope.tenderDate works and outputs this date correctly. That is why I find it weird that when I type it in like this it selects the date in the date picker but not in the inputfield.

$ = function() {
$scope.dt = moment("2017-08-02", "YYYY-MM-DD").format();

And without the use of momentjs and write it like this it all works. And shows the correct date "2017-08-02" like that.

$ = function() {
$scope.dt = new Date(2017, 7, 2);

Maybe you know a good way to get the date from json in the datepicker.

Answer Source

As mentioned in the docs You need to assign the $scope.dt a value as if it would be a normal Javascript Date format.

In order to achieve that you need to use .toDate() instead of .format().

Your code would look like:

$ = function() {
    $scope.dt = moment("2017-08-02", "YYYY-MM-DD").toDate();