Using Pikaday with Angular Formly

21st December 2015 | Tags:

Pika­day is a great lit­tle date selec­tor plu­gin. Whilst the Pika­day Angu­lar plu­gin makes it easy to inte­grate into an Angu­lar appli­ca­tion, there’s slightly more work involved in get­ting it work­ing with Angu­lar Formly.

If you haven’t used Formly, it’s essen­tially a frame­work for cre­at­ing forms declar­a­tively; rather than writ­ing out its HTML by hand. It takes care of ren­der­ing the rel­e­vant con­trols and their labels, enables you to attach val­i­da­tion and it will inject error mes­sages for you, and a num­ber of other features.

The prob­lem with using Pika­day with Formly is that you’re prob­a­bly going to want to trans­late the dis­play value of the plu­gin into a for­mat more suit­able for stor­age. For exam­ple in one form you might dis­play “12 Jan­u­ary 2016″ but want it bound to a model in ISO 6031 format.

This is achieved by attach­ing a light­weight con­troller to the form ele­ment which mon­i­tors the plu­gin for changes, then sets the under­ly­ing model accord­ingly. Addi­tion­ally it sets the ini­tial value if required.

Note that you still need Pika­day Angu­lar:

bower install --save pikaday-angular

Now you can cre­ate a new Formly type by plac­ing the fol­low­ing code in, for exam­ple, your application’s run() section:

  name: 'pikaday',
  template: '<input class="form-control" pikaday="theDate" on-select="select(pikaday)" />',        
  link: function($scope, el, attrs, ctrl) {
    // Set the initial value
    var value = $scope.model[$scope.options.key];          
    $scope.$$childHead.pikaday.setDate( new Date(value) );          
  controller: ['$scope', function ($scope) {          
    $ = function( pikaday ) {
      // Set the relevant property on the model
      $scope.model[$scope.options.key] = pikaday.getDate().toISOString();            
  wrapper: ['bootstrapLabel', 'bootstrapHasError']

You’ll prob­a­bly want to adapt cer­tain parts accord­ing to your pref­er­ences; for exam­ple, this is Boot­strap flavoured, as you can see from the class name (form-control) and the addi­tion of Bootstrap-​specific ele­ment wrap­pers. You may also wish to choose an alter­na­tive for­mat for the under­ly­ing value; I’m using toISOString(), but you might pre­fer a UNIX time­stamp, for example.


No comments yet.

Links and images are allowed, but please note that rel="nofollow" will be automactically appended to any links.