Angular+JQ+Bootstrap

by ganarajpr

HTML

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.angularjs.org/1.0.0rc8/angular-1.0.0rc8.js"></script>
<div ng-controller="MyCtrl">
    <form>
        <h6>This is my form!</h6>
        <form-struct data="formData"></form-struct>
    </form>
    <hr />
    {{formData}}
    <hr />
    <button ng-click="formData.fields.push({name:'extra',type:'string',value:'hello'})">Add New</button>
</div>

JavaScript

var myApp=angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.formData = {
        title : "Form Test",
        fields : [{
                name : "FieldA",
                type : "string",
                value : "initial value, change me!"
            }, {
                name : "FieldB",
                type : "selection",
                options : ["1", "2", "3"],
                value : "2"
            }, {
                name : "FieldC",
                type : "struct",
                value :
                [{
                        name : "FieldC1",
                        type : "string",
                        value : "initial value"
                    }, {
                        name : "FieldC2",
                        type : "string",
                        value : "initial value"
                    }
                ]
            }
        ]
    };
}

myApp.directive('formStruct', function($compile) {
    return {
        restrict: 'E',
        scope:{ data: 'accessor' },
        link: function(scope, elm, attrs) {
            elm.append($compile(
            '<b>Struct {{data().name || data().title}}</b>'+
            '<div ng-repeat="field in data().value || data().fields">'+
                '<span ng-switch on="field.type">'+
                '<div ng-switch-when="string">'+
                    '{{field.name}}: <input ng-model="field.value" />'+
                '</div>'+
                '<div ng-switch-when="selection">'+
                    '{{field.name}}: <select ng-options="o for o in field.options" ng-model="field.value" ></select>'+
                '</div>'+
                '<div ng-switch-when="struct">'+
                    '<form-struct data="field"></form-struct>'+
                '</div>'+
                '</span>'+
            '</div>'
            )(scope));
        }
    };
});