如何将日期从ng-model绑定到HTML 5日期输入?

时间:2017-04-14 21:44:13

标签: angularjs

我正在尝试将模型中的日期绑定到HTML 5日期输入,如下所示:

<input type="date" ng-model="data.employeeCase.initialConsultDate" />

该属性在我的JSON中看起来像这样:

"initialConsultDate": "2017-04-20T04:00:00",

我可以通过这样的硬编码来设置它:

<input type="date" value="2017-04-20">

如何使用模型中的值设置我喜欢的并使用ng-model绑定它?

更新1: 下面的答案1为我工作。

我只想展示我的实施,万一有人遇到麻烦。

    /***** Get Employee Case By ID *****/
    $scope.getEmployeeCase = function (caseId) {
        //console.log("In GetEmployeeCase");
        //console.log(caseUrl + '/' + caseId);
        $http.get(caseUrl + '/' + caseId)
           .then(function (response) {
               // Test front end exception message;
               // throw "test exception";
               $scope.data.employeeCase = response.data;

               var date = new Date(response.data.initialConsultDate);
               $scope.sanitizedInitialConsultDate = $filter('date')(date, "yyyy-MM-dd")
                              })
           .catch(function (error) {
               $scope.data.caseDetailError = error;
               $scope.data.error = error;
           });
    }

<th>Intitial Consult Date:</th>
    <td>
        <input type="date" ng-value="sanitizedInitialConsultDate" ng-model="data.employeeCase.initialConsultDate" />
    </td>

1 个答案:

答案 0 :(得分:1)

从json中获取日期字符串并创建new Date()。然后,使用Angular的$filter服务根据您的需要格式化日期。

var app = angular.module('plunker', []);

 app.controller('MainCtrl', function($scope, $filter) {

 var json = {
  initialConsultDate: "2017-04-20T04:00:00"
 };

 var date = new Date(json.initialConsultDate);

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


});

然后,使用ng-value设置日期输入:

<input type="date" ng-value="date">

在这里演示:http://plnkr.co/edit/UEcWvpyO1df4SXhvdNla?p=preview