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">
   <head>
      <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 );
               }
            } );
      </script>
      <style>
         #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;
         }
      </style>
   </head>
   <body ng-controller="myController">
      <metawidget id="metawidget" ng-model="person">
         <button ng-click="save()">Save</button>
      </metawidget>

   </body>
</html>

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.

5 comments:

Davor said...

Hi, address book example is awesome to see mix with angularjs, but I must admit I found very hard to find what types are available, for example, If I want to change enum for Gender (select box) with radio or checkbox buttons, how do I do that, how do I setup properties for that? Can't find example in the javascript documentation :( Is there a list of available types and how do I use them in json format? thank you

Richard Kennard said...

Davor,

Thanks for your interest!

Yes a list of default types is here: http://metawidget.org/doc/reference/en/html/ch06s02.html#section-widgetbuilders-javascript-default

I will write a blog post about using radio/checkbox buttons.

Regards,

Richard.

Davor said...

Oh, that is what I was searching for! :)

great, can't wait for the blog post about radio/checkbox buttons..

thanks Richard!

Richard Kennard said...

Blog now posted: http://blog.kennardconsulting.com/2013/09/angularjs-ui-generator-custom-widgets.html

Please let me know if it answers your question!

Davor said...

This is awesome Richard! Yes it does. Thank you very much!