如何在angularjs中使用ui-date时将初始值设置为ng-model [英] How to set the initial value to ng-model when using ui-date in angularjs
问题描述
我的模型基于 JSON 对象,日期为 2012-12-13T00:00:00-07:00
My model is based off of a JSON object and the date comes in as 2012-12-13T00:00:00-07:00
我想使用日期选择器 ui-date.
I want to use the date picker ui-date.
我有以下有效的代码.
<input ng-model="course.startDate" value="{{item.startDate | date: 'MM/dd/yyyy'}}" ui-date ng-required="true">
但是,我认为我不应该使用 value="{{item.startDate | date: 'MM/dd/yyyy'}}"
部分,但没有它,输入不会不加载模型中的值.
However,I don't think I should be using the value="{{item.startDate | date: 'MM/dd/yyyy'}}"
part but without it the input doesn't load with the value from the model.
当我选择一个日期时,模型已绑定并正常运行,但在页面加载时显示为空.
The model is bound and functions correctly when I chose a date, it just shows up empty when the page loads.
初始化这个输入的正确方法是什么?
What is the correct way to initialize this input?
推荐答案
使用 ui-date
和 ng-model
应该就够了:
Using ui-date
and ng-model
should be enough:
<div ng-controller="MyCtrl">
<input ng-model="date" ui-date>
</div>
Provided that the MyCtrl
is defined like this:
假设 MyCtrl
是这样定义的:
Here is a jsFiddle: http://jsfiddle.net/MvGFF/2/
What you must know is that the ui-date
expects model value to be an instance of Date, maybe you are passing a string (or other type) value?
这是一个 jsFiddle:http://jsfiddle.net/MvGFF/2/>
您必须知道的是,ui-date
期望模型值是 Date 的实例,也许您正在传递一个字符串(或其他类型)值?
If your model holds values that are strings and you still want to use a date-picker you need to add the ui-date-format
directive like in this example:
如果您的模型包含字符串值,而您仍想使用日期选择器,则需要添加 ui-date-format
指令,如下例所示:
<input ng-model="date" ui-date ui-date-format>
where the controller is defined like so:
控制器定义如下:
Here is a jsFiddle: http://jsfiddle.net/d4xz2/1/
这篇关于如何在angularjs中使用ui-date时将初始值设置为ng-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!