我正在尝试使用代表时间戳的<input type="datetime-local>
呈现ng-model
字段:
<input type="datetime-local" ng-model="object.value">
与
$scope.object.value = 1433109600000;
控制台显示[ngModel:datefmt]
错误。
如何正确绑定$scope.object.value
到输入字段? (时间戳来自nestest对象中的Web服务)
答案 0 :(得分:10)
必须是日期对象:
$scope.object = {
name: 'Demo',
value: new Date(1433109600000)
}
或创建指令:
app.directive('bindTimestamp', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$formatters.push(function (value) {
return new Date(value);
});
}
};
});
答案 1 :(得分:1)
完成@ karaxuna的回答,多亏了他,以下是完整的指令及其测试:
// 2016-02-19 09:56:51.396ms
var dt = 1455872211396;
function buildInputDateElement(inputType) {
var element = angular.element('<input type="' + inputType + '" ng-model="myDate" bind-timestamp>');
$compile(element)($scope);
$scope.$digest();
return element;
}
it('bindTimestamp : input[date]', function () {
var formatedDate = '2016-02-19';
/** A timestamp */
$scope.myDate = dt;
var element = buildInputDateElement("date");
expect(element.val()).toEqual(formatedDate);
//** Already a <Date> */
$scope.myDate = new Date(dt);
element = buildInputDateElement("date");
expect(element.val()).toEqual(formatedDate);
});
it('bindTimestamp : input[datetime-local]', function () {
var formatedDate = '2016-02-19T09:56:51.396';
/** A timestamp */
$scope.myDate = dt;
var element = buildInputDateElement("datetime-local");
expect(element.val()).toEqual(formatedDate);
/** Already a <Date> */
$scope.myDate = new Date(dt);
element = buildInputDateElement("datetime-local");
expect(element.val()).toEqual(formatedDate);
});
});
茉莉花测试:
describe(&#39; bindTimestamp:timestamps&#39;,function(){
{{1}}