1
我試圖在控制器中分配一個input[date]
控件的初始值。以編程方式更改AngularJS輸入[日期]
從AngularJS input[date]
文檔,
模型必須始終爲Date對象,否則角將拋出 錯誤。
他們提供瞭如何在控制器(粘貼在simplified version),上Plunker初始化工作的input[date]
工作的例子。
<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>
當我做我的應用程序一樣,我總是得到以下信息:
The specified value 'Sun Nov 09 2014 00:00:00 GMT+0100 (CET)' does not conform to the required format, 'yyyy-MM-dd'
和控制不inititlized。似乎它期待ISO格式的字符串,而不是有效的日期對象。
在Set default value of HTML5 date input field with angularJS提出了一種替代的方法:
<input type="date" ng-model="date" value="{{date}}">
...
$scope.date = $filter("date")(Date.now(), 'yyyy-MM-dd');
它只是一個assings 「YYY-MM-DD」 串到模型中。根據文檔,這應該會引發錯誤,因爲字符串不是有效的日期對象,但是這第二種方法適用於我,但很有趣,如果您在修改後的原始文件Plunker中使用它,則不適用。
- 什麼可以搞亂我的
input[dates]
,所以我不能設置 控制器中的值作爲spected? - 爲什麼alt方法爲我工作 (和其他人),但不提供簡單的演示工作?
這裏是從我的代碼一些摘錄其中輸入[型],創建並在那裏assiged初始值:
的index.html
<input type="date" name="input", ng-model="value" />
控制器
.controller("UploadsCtrl",["$scope","$filter", function($scope, $filter) {
// $scope.value = new Date(2013, 22, 9); // Not working
$scope.value = "2015-10-10"; // Working!!!!
...
實際上很奇怪。 Angular使用'return toString.call(value)==='[object Date]';'爲了驗證一個Date對象,你的情況應該起作用。你可以調試到Angular看看爲什麼它在代碼庫中失敗了嗎? – Rebornix 2015-02-07 12:48:00
AngularJS版本? – tasseKATT 2015-02-08 16:06:27
AngularJS版本:1.2.28 – 2015-02-09 18:08:25