Tuesday, August 13, 2013

How to generate a UI from JSON Objects using AngularJS

My previous minimal post has been quite popular, so I thought I'd do an AngularJS version. As expected, all that Angular goodness makes it even cleaner:

<html ng-app="myApp">
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
      <script src="http://metawidget.org/js/3.5/metawidget-core.min.js" type="text/javascript"></script>
      <script src="http://metawidget.org/js/3.5/metawidget-angular.min.js" type="text/javascript"></script>
      <script type="text/javascript">
         angular.module( 'myApp', [ 'metawidget' ] )
            .controller( 'myController', function( $scope ) {
               $scope.person = {
                  firstname: 'Homer',
                  surname: 'Simpson',
                  age: 36

               $scope.save = function() {
                  console.log( $scope.person );
            } );
         #metawidget {
            border: 1px solid #cccccc;
            width: 250px;
            border-radius: 10px;
            padding: 10px;
            margin: 50px auto;
            display: block;
         #metawidget button {
            display: block;
            margin: 10px auto 0px;
   <body ng-controller="myController">
      <metawidget id="metawidget" ng-model="person">
         <button ng-click="save()">Save</button>


This will handily render:

Clicking the Save button will print the results to the console.

Of course Metawidget can extend this further to support form validation, alternate layouts, third-party components, and much more. To see how, the best place to start is the tutorial.

Thursday, August 8, 2013

NoSQL UI Generator

I did an experiment combining MongoDB, JAX-RS, AngularJS and Metawidget to show how Metawidget lets you render NoSQL objects straight to the client. The advantage of this is that your client can dynamically adapt to whatever data is in your NoSQL database, without having to duplicate definitions between client and server. It's a MongoDB UI Generator!

Of course, there's nothing MongoDB-specific (or NoSQL-specific) about Metawidget. But it was great to see how easily these technologies played together. The only real gotcha was this bug, which I worked around by 'unwrapping' the $oid field:

// MongoDB's built-in ObjectId uses an $oid field, which AngularJS doesn't like to serialize

contact.put( "_id", new ObjectId().toString() );

You can download complete sample source code here. You'll need to deploy it on a Java EE compatible server (I used JBoss 7.1.1.Final) for JAX-RS, and MongoDB should be installed.

Feedback welcome!