Dynamic Directives with Angularjs

Asked

Viewed 467 times

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 configuration of the fields.

Following example:

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

Is there any way to create directives dynamically, 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 generate directives by returning for example(with smaller Priority):

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

Existing of course, a way to compile each after ng-repeat.

Some way to do this?

  • I think it’s best to generate an HTML and append it to a div with the attribute ng-bind-unsafe, if I’m not mistaken. But I’ve never done it. I just think it works.

  • No use, need to use other attributes, mount selects, use masks...

  • That’s why you need the attribute ng-bind-unsafe. If pro mount you mean "use", I believe it works. But as I said, just testing.

1 answer

2

I was able to solve it this way:

//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'
        }
    };
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.