How can I load value on input date with angular?

最后都变了- 提交于 2020-01-07 03:04:26

问题


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

On 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?


回答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.




回答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 " />



回答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'}}">


来源:https://stackoverflow.com/questions/41642076/how-can-i-load-value-on-input-date-with-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!