我想在AngularJS中使用jquery timepicker插件创建一个timepicker指令。 (我无法获得任何现有的角度计时器在IE8中工作)。如何在AngularJS中正确设置我的timepicker指令的值?
到目前为止,我已经能够获得指令,以便在选择时间时更新范围。但是,我现在需要完成的是获取输入来显示时间,而不是页面第一次加载时模型值的文本。请看下图:
这是表明: 这就是我想要的:
这里是我的指令:
'use strict';
playgroundApp.directive('timePicker', function() {
return {
restrict: 'A',
require: "?ngModel",
link: function(scope, element, attrs, controller) {
element.timepicker();
//controller.$setViewValue(element.timepicker('setTime', ngModel.$modelValue));
//ngModel.$render = function() {
// var date = ngModel.$modelValue ? new Date(ngModel.$modelValue) : null;
//};
//if (date) {
// controller.$setViewValue(element.timepicker('setTime', date));
//}
element.on('change', function() {
scope.$apply(function() {
controller.$setViewValue(element.timepicker('getTime', new Date()));
});
});
},
};
})
注释代码是我一直尝试,但它不没有工作。我得到一个读取错误,ngModel未定义。因此,为了澄清,当页面第一次加载时,如果该输入字段有模型,我希望输入只显示时间,就像在选择一个值后显示的那样。
谢谢。
编辑:
好,使得一些试验和错误更改后,我的链接功能如下:
link: function (scope, element, attrs, controller) {
if (!controller) {
return;
}
element.timepicker();
var val = controller.$modelValue;
var date = controller.$modelValue ? new Date(controller.$modelValue) : null;
controller.$setViewValue(element.timepicker('setTime', controller.$modelValue));
//ngModel.$render = function() {
// var date = ngModel.$modelValue ? new Date(ngModel.$modelValue) : null;
//};
if (date) {
controller.$setViewValue(element.timepicker('setTime', date));
}
element.on('change', function() {
scope.$apply(function() {
controller.$setViewValue(element.timepicker('getTime', new Date()));
});
});
},
这不会给我任何错误,但是$ modelValue始终为NaN 。这里是我的控制器代码:
$scope.startTime = new Date();
$scope.endTime = new Date();
及相关HTML:
<input id="startTime" ng-model="startTime" time-picker/>
<input id="endTime" ng-model="endTime" time-picker />
有没有别的东西,我需要做什么?
您使用哪个timepicker插件? –
https://github.com/jonthornton/jquery-timepicker#timepicker-plugin-for-jquery –