Skip to content

Instantly share code, notes, and snippets.

@blaryjp
Created January 21, 2014 21:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save blaryjp/8548592 to your computer and use it in GitHub Desktop.
Save blaryjp/8548592 to your computer and use it in GitHub Desktop.
Angular directive for Bootstrap3 datetimepicker - http://eonasdan.github.io/bootstrap-datetimepicker/
angular.module('angularApp').
directive('dt', function(){
return {
require: '?ngModel',
restrict: 'A',
link: function ($scope, element, attrs, controller) {
var updateModel, onblur;
if (controller !== null) {
updateModel = function () {
if (element.data("DateTimePicker").minViewMode === element.data("DateTimePicker").viewMode) {
element.data("DateTimePicker").hide();
element.blur();
}
};
onblur = function () {
var date = element.datetimepicker().data("DateTimePicker").getDate();
return $scope.$apply(function () {
return controller.$setViewValue(date);
});
};
controller.$render = function () {
var date = controller.$viewValue;
if (angular.isDefined(date) && date != null && moment.isMoment(date)) {
element.datetimepicker().data("DateTimePicker").setDate(date);
} else if (angular.isDefined(date)) {
throw new Error('ng-model value must be a Moment - currently it is a ' + typeof date + '.');
}
return controller.$viewValue;
};
}
return attrs.$observe('dt', function (value) {
var options;
options = { }; //<--- insert your own defaults here!
if (angular.isObject(value)) {
options = value;
}
if (typeof (value) === "string" && value.length > 0) {
options = angular.fromJson(value);
}
return element.datetimepicker(options).on('change.dp', updateModel).on('blur', onblur);
});
}
};
});
@kranthitech
Copy link

Thanks blary :) . Could you please give a small example of this directive in use.

@yuanjingxp
Copy link

<input type="text" size="16" class="form-control" value="{{vm.Date}}" ng-model="Date" dt>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment