Dynamic directives with angular js

1

I'm building an application that needs to render a dynamic form.

The form data comes from a json , and in it, I have the fields configuration.

Here's an example:

{
"Fields": [
{
  "title": "Assunto",
  "type": "text"
},
{
  "title": "Email da tia",
  "type": "email",
}]
}

Is there any way to dynamically create policies, using attribute or class, setting high priority?

For example:

<section ng-repeat="field in Fields">
   <field-builder data-type="field.type"></field-builder>
</section>

And in this directive, field builder, it generates directives returning for example (with minor priority):

<span class="text"></span>
<span class="email"></span>

Of course, a way to compile each one after ng-repeat.

Any way to do this?

    
asked by anonymous 26.02.2015 / 23:29

1 answer

2

I was able to resolve it as follows:

//View aonde é renderizado os elementos:
<fieldset>
       <section ng-repeat="field in preview.model.Field">
            <field-builder field-model="field"></field-builder>
      </section>
</fieldset>

//Diretiva com templateCache para evitar múltiplas requisições.
function fieldBuilder($compile, viewsUrl, $templateCache, $http) {
    var linker = function (scope, element) {
        //Neste local tenho as partials pré definidas para cada input que preciso gerar.
        var templateUrl = viewsUrl + 'templates/field/' + scope.field.type + '.html';
                               //Efetua o cache
        $http.get(templateUrl, {cache: $templateCache})
                .then(function (response) {
                    element.html(response.data);
                    $compile(element.contents())(scope);
                });
    };
    return {
        restrict: "E",
        transclude: true,
        link: linker,
        scope: {
            field: '=fieldModel'
        }
    };
}
    
27.02.2015 / 16:21