[AngularJS] datepicker with jQuery


The best way to implement a datepicker on website, in my opinion, is through HTML5 input tag with type=date. This input type, however, is not well-supported. AngularJS is a very promising extension for HTML, so I did some study on how to implement datepicker with AngularJS. The easiest way is to combine AngularJS directive and jQuery datepicker. The following is demo and complete source code:

Demo

directive.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<!doctype html>
<html ng-app="demo">
<head>
  <meta charset="utf-8">
  <title>datepicker with AngularJS and jQuery</title>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
</head>
<body ng-controller="myCtrl">

<input type="text" ng-model="date" datepicker/>
{{date}}

<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script src="directive.js"></script>
<!-- tested on AngularJS 1.3.11 and 1.0.4 -->
</script>
</body>
</html>
directive.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// tested on AngularJS 1.3.11 and 1.0.4
angular.module('demo', [])
  .directive('datepicker', ['$parse', function($parse) {
    var directiveDefinitionObject = {
      restrict: 'A',
      link: function postLink(scope, iElement, iAttrs) {
        iElement.datepicker({
          dateFormat: 'yy-mm-dd',
          onSelect: function(dateText, inst) {
            scope.$apply(function(scope){
              $parse(iAttrs.ngModel).assign(scope, dateText);
            });
          }
        });
      }
    };
    return directiveDefinitionObject;
  }])
  .controller('myCtrl', ['$scope', function($scope) {
    $scope.date = "1212-12-12";
  }]);

Sample code tested on AngularJS 1.0.4 and 1.3.11


References:

[1]AngularJS: Developer Guide: Directives
[2]Datepicker Widget | jQuery UI API Documentation
[3]jsFiddle demo