AngularJS封装jQuery DateTimepicker

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 lang="en">
		<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"></link>
		<link href="jQuery-Timepicker-Addon/jquery-ui-timepicker-addon.css" type="text/css" />
		<link href="jQuery-Timepicker-Addon/demos.css" 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>

运行效果:

AngularJS封装jQuery DateTimepicker_第1张图片

AngularJS封装jQuery DateTimepicker_第2张图片
AngularJS封装jQuery DateTimepicker_第3张图片

你可能感兴趣的:(JavaScript,jquery,AngularJS,datetimepicker)