Thursday, May 22, 2014

AngularJS: Changing the date format of dynamically generated components

I was recently asked:

" a better approach to set a different date formatting, besides from hacking it in metawidget-angular.js"

The answer is yes! Metawidget is designed around a five stage pluggable pipeline, which offers well-researched extension points to accomodate most UI requirements.

The easiest approach to this particular problem is to add a little WidgetProcessor to tweak Metawidget's standard date formatting (if you want to introduce a whole new control instead, better to go with a WidgetBuilder, as shown here). Here's a complete example:

<html ng-app="myApp">
      <script src="" type="text/javascript"></script>
      <script src="" type="text/javascript"></script>
      <script src="" type="text/javascript"></script>
      <script type="text/javascript">
         angular.module( 'myApp', [ 'metawidget' ] ).controller( 'myController', function( $scope ) {
         $scope.metawidgetConfig = {
            addWidgetProcessors: [ function( widget, elementName, attributes, mw ) {
               if ( attributes.type === 'date' ) {
                  widget.setAttribute( 'ng-bind', widget.getAttribute( 'ng-bind' ) + ":'d MMMM yyyy'" );
               return widget;
            } ]

         $scope.person = {
            firstname: 'Homer',
            surname: 'Simpson',
            date: new Date( 1953, 5, 12 )
      } );
         #metawidget {
            border: 1px solid #cccccc;
            width: 250px;
            border-radius: 10px;
            padding: 10px;
            margin: 50px auto;
            display: block;
   <body ng-controller="myController">
      <metawidget id="metawidget" ng-model="person" read-only="true" config="metawidgetConfig" />

Feedback welcome!