'Change AngularJS input[date] programmatically
I'm trying to assing an input[date]
control an initial value in the controller.
From AngularJS input[date]
documentation,
The model must always be a Date object, otherwise Angular will throw an error.
They provide a working example of how to init an input[date]
in the controller (Pasted a simplified version), that works on Plunker.
<script>
angular.module('dateInputExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.value = new Date(2013, 9, 22);
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<input type="date" id="exampleInput" name="input" ng-model="value" />
</form>
When I do the same in my application I always get the following message:
The specified value 'Sun Nov 09 2014 00:00:00 GMT+0100 (CET)' does not conform to the required format, 'yyyy-MM-dd'
and the control is not initialized. Seems that it is expecting a string in ISO format and not a valid Date Object.
In Set default value of HTML5 date input field with angularJS an alternate method is proposed:
<input type="date" ng-model="date" value="{{date}}">
...
$scope.date = $filter("date")(Date.now(), 'yyyy-MM-dd');
It just assigns a "yyy-MM-dd" string to the model. According to the docs this should throw an error, since a string is not a valid Date Object, but this second method works for me, but funny, does not work if you use it in the modified original Plunker, adapted to use this method.
- What can be messing my
input[dates]
so I can't set the value in the controller as expected? - Why is the alternate method working for me (and others) but not working in the simple demo provided?
Here are some excerpts from my code where the input[type] is created and where it is assigned the initial value:
index.html
<input type="date" name="input", ng-model="value" />
Controller
.controller("UploadsCtrl",["$scope","$filter", function($scope, $filter) {
// $scope.value = new Date(2013, 22, 9); // Not working
$scope.value = "2015-10-10"; // Working!!!!
...
Solution 1:[1]
Angular 1.2.x does not support input[date].
Update to 1.3.13 solves the problem.
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 | David Casillas |