1

[AngularJS] datepicker with jQuery

 2 years ago
source link: http://siongui.github.io/2013/02/06/angularjs-datepicker-with-jquery/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[AngularJS] datepicker with jQuery

Updated: February 23, 2015

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

<!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

// 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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK