'How can I load value on input date with angular?

I'm programming with Angular 1.5.5 and I'm using Materialize CSS 0.97.6.

On my controller, I have $scope.myDate = '2017-01-13T02:06:40' In the HTML file, I have <input type='date' class='form-control datepicker' value="{{(myDate | date: 'dd/MM/yyyy')}}">

But the input field doesn't show anything.

If I put <input type='date' class='form-control datepicker' value="13/01/2017"> it works.

I did it to check the myDate variable <div ng-bind="myDate | date : 'dd/MM/yyyy'"></div> and it works too.

So, anyone can explain why the value is not being loaded to input when I use the variable?



Solution 1:[1]

As for any other input, you bind the value in the input field with your model using ng-model.

And as the documentation says:

The model must always be a Date object, otherwise Angular will throw an error. Invalid Date objects (dates whose getTime() is NaN) will be rendered as an empty string.

Solution 2:[2]

You can pass the date from scope to the input[date] with attribute ng-model. You can see the full documentation here: https://docs.angularjs.org/api/ng/input/input%5Bdate%5D

In you code, you need to change myDate to a Date object, not string

$scope.myDate = new Date(2013, 9, 22);

and also in your template, the input[date] will be like this:

<input type='date' ng-model="myDate " />

Solution 3:[3]

There is no way possible to change the format of html5 input date type, for more info see the previous answer below:

Is there any way to change input type="date" format?

So if the format is mandatory you can use the Datepicker Popup element in angular ui.bootstrap library for example where you can set the format directly, this is their plunker example :

otherwise if the format is not mandatory to you, just instantiate a new date object and it will work like this:

$scope.myDate = new Date('2017-01-13T02:06:40');
<input type="date" class="form-control datepicker" ng-model="myDate">

or if you don't care about editing the date and you want to only show it you can just change the type of the input to text and it will also work like this:

$scope.myDate = '2017-01-13T02:06:40';
<input type="text" class="form-control datepicker" ng-readonly="true" style="background: #ffffff;" value="{{myDate | date: 'dd/MM/yyyy'}}">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JB Nizet
Solution 2 Anthony C
Solution 3 Community