DateTimePickerDirective.js
angular.module('myApp.directives',[])
.directive('datetimepicker', function() {
return {
//強制AngularJS把指令限定為隻支援屬性
restrict: 'A',
//總是和ng-model配合使用
require:'?ngModel',
scope: {
//此方法需要與預先定義好,然後傳遞給視圖控制器中的指令
select: '&' //把我們所引用的select函數綁定到右邊的作用域中
},
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return;
var optionsObj = {};
optionsObj.timeFormat = 'HH:mm:ss';
var updateModel = function(dateTimeTxt) {
scope.$apply(function() {
//調用AngularJS内部的工具更新雙向綁定關系
ngModel.$setViewValue(dateTimeTxt);
});
};
optionsObj.onSelect = function(dateTimeTxt, picker) {
updateModel(dateTimeTxt);
if(scope.select) {
scope.$apply(function() {
scope.select({date: dateTimeTxt});
});
}
};
ngModel.$render = function() {
//使用AngularJS内部的'binding-specific'變量
element.datepicker('setDate', ngModel.$viewValue || '');
};
element.datetimepicker(optionsObj);
}
};
});
DateTimePickerController.js
var app = angular.module('myApp', ['myApp.directives']);
app.controller('MainCtrl', function($scope) {
$scope.myText = 'Not Selected';
$scope.currentDateTime = '';
$scope.updateMyText = function(dateTime) {
$scope.myText = 'Selected';
};
});
DateTimePickerHtml.html
<!DOCTYPE html>
<html ng-app="myApp">
<head >
<meta charset="utf-8"></meta>
<title>AngularJS DateTimepicker</title>
<script src="jquery/jquery-1.8.3.js"></script>
<script src="jquery-ui/js/jquery-ui-1.9.2.js"></script>
<script src="angular/angular.js"></script>
<link rel="stylesheet" href="jquery-ui/css/custom-theme/jquery-ui-1.9.2.css" target="_blank" rel="external nofollow" ></link>
<link href="jQuery-Timepicker-Addon/jquery-ui-timepicker-addon.css" target="_blank" rel="external nofollow" type="text/css" />
<link href="jQuery-Timepicker-Addon/demos.css" target="_blank" rel="external nofollow" rel="stylesheet" type="text/css" />
<script src="jQuery-Timepicker-Addon/jquery-ui-timepicker-addon.js" type="text/javascript"></script>
<script src="directive/DateTimePickerDirective.js"></script>
<script src="controller/DateTimePickerController.js"></script>
<!--中文-->
<script src="jquery-ui/js/jquery.ui.datepicker-zh-CN.js" type="text/javascript" charset="gb2312"></script>
<script src="jquery-ui/js/jquery-ui-timepicker-zh-CN.js" type="text/javascript"></script>
</head>
<body ng-controller="MainCtrl">
<input id="dateField" datetimepicker ng-model="$parent.currentDateTime" select="updateMyText(dateTime)"></input>
<br></br>
{{myText}} - {{currentDateTime}}
</body>
</html>
運作效果:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiInBnauYmZjZTMmVDMhJTYh1SY2YmYtgjNwMTLxczYz0SOzMjNwkDMx8CX0ETN28CXwATMw8CX05WZth2YhRHdh9CXkF2bsBXdvwVbvNmLllXZ0lmLywGZvw1LcpDc0RHaiojIsJye.jpg)