我想在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 –