I took all the code from a detailed example here: http://angular-ui.imtqy.com/bootstrap/#/datepicker and wrapped it in my own directive. That way, I can simply discard an unlimited number of datepickers to my page and specify a model for each of them to bind. I donβt need to control the transmission of duplicate settings or set unique variables to track the status of βopenβ, I just put 1 line of code:
<div my-date-picker my-date-picker-model="myDate1"></div> <div my-date-picker my-date-picker-model="myDate2"></div> <div my-date-picker my-date-picker-model="myDate3"></div>
The user can then toggle each date selection open / close, and the values ββwill be updated in myDate1 , myDate2 and myDate3 respectively. The open / closed status is now encapsulated in the directive and out of mind.
To implement the directive, I copied the code for the "JS" tab to the controller, and I copied the code for the "Markup" tab to this template. At the end, I added 1 bit of code to update the value of the parent area:
$scope.$watch('dt', function(newVal, oldVal) { $scope.myDatePickerModel = newVal; });
At the beginning of the controller, I changed $ scope.today to initialize the value from the parent scope, instead of using the system clock:
$scope.init = function() { $scope.dt = $scope.hxDatePickerModel; }; $scope.init();
The directive uses the selection area and two-way binding to the attribute that defines the model of the parent area:
scope: { myDatePickerModel: '=' }
Here is the full directive code:
app.directive('myDatePicker', function() { function link(scope, element, attrs) { } function controller($scope) { $scope.init = function() { $scope.dt = $scope.myDatePickerModel; }; $scope.init(); $scope.clear = function () { $scope.dt = null; }; // Disable weekend selection $scope.disabled = function(date, mode) { return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) ); }; $scope.toggleMin = function() { $scope.minDate = $scope.minDate ? null : new Date(); }; $scope.toggleMin(); $scope.open = function($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']; $scope.format = $scope.formats[0]; $scope.$watch('dt', function(newVal, oldVal) { $scope.myDatePickerModel = newVal; }); } return { restrict: 'A', templateUrl: 'datepicker.html', link: link, controller: controller, scope: { myDatePickerModel: '=' } } });
And here is the full datepicker.html code, a template for this directive:
<p class="input-group"> <input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" /> <span class="input-group-btn"> <button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button> </span> </p>