Wednesday, May 14, 2014

AngularJS: Create editable tables with dynamic columns (Part 2)

Following on from my previous post, I was asked:

"[In your post the] table columns are rendered using html input control with type="text"... [Can the user] add/edit new object in accordance with json schema (checkbox for boolean, dropdown for enum,...)?"

This is where Metawidget really shines. Metawidget is designed to be lightweight and embedded multiple times on a page - wherever you need small pieces of UI generation. So we can easily use a Metawidget at the foot of each column:

The implementation is almost the same as before, except instead of instantiating an <input type="text">, the editable table instantiates another <metawidget> tag:

var nestedMetawidget = $( '<metawidget ng-model="newRow.' + columns[loop] + '" config="metawidgetConfig">' );
tr2.append( $( '<td>' ).append( nestedMetawidget ) );

The hardest part is passing the row schema metadata through to the editable table:

$scope[rowSchemaKey] = inspectionResult;
var widget = $( '<table>' ).attr( 'edit-table', '' ).attr( 'schema', rowSchemaKey );

You can download a complete example here. You can also take this approach further. Feedback welcome!