A simple implementation of datepicker using AngularJs Boostrap.
Template:
<!DOCTYPE html> <html ng-app="app"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.js"></script> <script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.js"></script> <script src="datepicker.js"></script> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body ng-controller="DatepickerDemoCtrl" style="padding-top: 50px"> <div class="container"> <div class="row"> <div class="col-md-3"> <p class="input-group"> <input type="text" class="form-control" datepicker-popup="dd-MMMM-yyyy" ng-model="dt" is-open="opened" min-date="minDate" max-date="maxDate" datepicker-options="dateOptions" ng-required="true" show-button-bar="false"/> <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> </div> </div> </div> </body> </html>
Script:
var app = angular.module('app', ['ui.bootstrap']); app.controller('DatepickerDemoCtrl', function ($scope) { $scope.dt = new Date(); $scope.minDate = new Date(); $scope.maxDate = new Date(); $scope.maxDate.setMonth($scope.maxDate.getMonth() + 1); $scope.dateOptions = { startingDay: 1, showWeeks: false }; $scope.opened = false; $scope.open = function($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = !$scope.opened; }; }); app.directive('datepickerPopup', function (){ return { restrict: 'EAC', require: 'ngModel', link: function(scope, element, attr, controller) { //remove the default formatter from the input directive to prevent conflict controller.$formatters.shift(); } } });
Notes:
- Used a custom directive ‘datepickerPopup’ taken from here so that default date would have correct display formatting
- Unsure why it’s not working when local files are used, so instead CDN files are referenced. Will find out why? 🙂
Advertisements