完成@ karaxuna的回答,感謝他,以下是完整的指令及其測試:
directivesApp.directive('bindTimestamp', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
var minDate = attrs.min ? new Date(attrs.min) : null;
var maxDate = attrs.max ? new Date(attrs.max) : null;
ngModel.$formatters.push(function (value) {
var dt = value;
if (!angular.isDate(dt) && angular.isNumber(dt)) {
// It's a timestamp --> needs to be converted to a <Date>
dt = new Date(value);
}
// truncate 'dt' to second if milliseconds are not to be displayed in input[datetime-local]
// dt.setMilliSeconds(0);
// truncate 'dt' to minute if seconds are not to be displayed in input[datetime-local]
// dt.setSeconds(0);
return dt;
});
// Default validators need to be overriden, otherwise they will always trigger "false" as they expect a <Date> object and not a number.
var MinMaxValidator = function (modelValue) {
var selectedDate = angular.timestampToDate(modelValue, scope.truncateSeconds);
this.validate = function (validateThreshold) {
if (angular.isDate(selectedDate)) {
return validateThreshold(selectedDate);
}
return true;
};
};
if (ngModel.$validators.min && minDate !== null) {
ngModel.$validators.min = function (modelValue) {
return new MinMaxValidator(modelValue).validate(function (selectedDate) {
return minDate <= selectedDate;
});
};
}
if (ngModel.$validators.max && maxDate !== null) {
ngModel.$validators.max = function (modelValue) {
return new MinMaxValidator(modelValue).validate(function (selectedDate) {
return maxDate >= selectedDate;
});
};
}
}
};
});
茉莉測試: 描述( 'bindTimestamp:時間戳',函數(){
// 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);
});
});
這是一個明確的觀點,但正如所述:該對象來自web服務,所以我不能修改該值... – Second2None
爲什麼你不能?例如:'return $ http.get('...')。then(function(result){result.value = new Date(result.value); return result});' - 這會被修改承諾 – karaxuna
另一個方式是爲此編寫指令。我也會寫,等一下)) – karaxuna