Set default value of HTML5 date input field with angularJS
Asked Answered
G

5

18

I am hoping to bind the default value I generated in moment to the date and time input field. I tried ng-model and directly binding it to the value attributes. But none of it seems to work. Is there a way to make it work?

Edit: Also, how to bind the time input field as well?

<body ng-app="myApp">
<div ng-controller="MyCtrl">
    <input type="date" ng-model="date" value="{{date}}">
        <p>{{date}}</p>
    <input type="time" ng-model="time" value="{{time}}">    
</div>

Here is a fiddle for it: http://jsfiddle.net/chrisyeung/bF9Pq/

Glaikit answered 28/11, 2013 at 8:57 Comment(1)
I changed moment() to new Date() in your fiddle and it seemed to workOshinski
F
31

If you're using chrome you have to specify the Date format as 'yyyy-MM-dd'.

$scope.date = $filter("date")(Date.now(), 'yyyy-MM-dd');

It simply won't work otherwise. Here's a working version http://jsfiddle.net/bF9Pq/4/

Faints answered 28/11, 2013 at 9:23 Comment(4)
this fiddle does not work on chrome33. It works on firefox27.Tridimensional
this worked for me on a chrome extension. Any idea why chrome expects yyyy-MM-dd?Fibrovascular
The value for date type was designed to follow this standard, tools.ietf.org/html/rfc3339#section-5.6. Thats why :(Belgrade
you better create an object out of your string: scope.date = new Date($filter("date")(Date.now(), 'yyyy-MM-dd'));Rebel
N
6

Working fiddle

{{date | date:'MM/dd/yyyy'}}

I changed the it to date and add date filter.

Niven answered 28/11, 2013 at 9:18 Comment(0)
I
4
value="{{date}}" 

causes init error: The specified value "{{datum_default}}" does not conform to the required format, "yyyy-MM-dd".

solution: do not set date in the template!

<input type="date" ng-model="date_code">

assign the date in controller!

$scope.date_code = new Date();
Inandin answered 24/4, 2016 at 8:31 Comment(0)
M
0

You could also do:

$scope.date = new Date().toLocaleDateString('en-CA');

Mannose answered 8/1, 2020 at 19:4 Comment(0)
C
0

With moment library, you can use this:

$scope.date = new Date()

If the value is already stored in database/ variable:

$scope.date = new Date(moment(varName).tz('Asia/Kolkata').format('L'))

moment.locale();         // en
moment().format('LT');   // 9:58 AM
moment().format('LTS');  // 9:58:18 AM
moment().format('L');    // 12/07/2020
moment().format('l');    // 12/7/2020
moment().format('LL');   // December 7, 2020
moment().format('ll');   // Dec 7, 2020
moment().format('LLL');  // December 7, 2020 9:58 AM
moment().format('lll');  // Dec 7, 2020 9:58 AM
moment().format('LLLL'); // Monday, December 7, 2020 9:58 AM
moment().format('llll'); // Mon, Dec 7, 2020 9:58 AM
Cosme answered 10/1, 2023 at 9:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.