2017-04-14 89 views
-1

我想从我的模型日期绑定到HTML 5日期输入这样的:如何将ng模型的日期绑定到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-模型绑定呢?

更新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

你按照那个角度介绍错误消息的建议吗? https://docs.angularjs.org/error/ngModel/datefmt?p0=2017-04-20T04:00:00。换句话说,'initialConsultDate'必须是'Date',而不是'string'。 – Claies

回答

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

+0

工程就像一个魅力:)谢谢。 – Sam