teepusink teepusink - 1 year ago 106
AngularJS Question

AngularJS - Directive template dynamic

How can I create a directive with a dynamic template?

'use strict';

app.directive('ngFormField', function($compile) {
return {
transclude: true,
scope: {
label: '@'
template: '<label for="user_email">{{label}}</label>',
// append
replace: true,
// attribute restriction
restrict: 'E',
// linking method
link: function($scope, element, attrs) {
switch (attrs['type']) {
case "text":
// append input field to "template"
case "select":
// append select dropdown to "template"

<ng-form-field label="First Name" type="text"></ng-form-field>

This is what I have right now, and it is displaying the label correctly. However, I'm not sure on how to append additional HTML to the template. Or combining 2 templates into 1.

Answer Source

Had a similar need. $compile does the job. (Not completely sure if this is "THE" way to do it, still working my way through angular)

http://jsbin.com/ebuhuv/7/edit - my exploration test.

One thing to note (per my example), one of my requirements was that the template would change based on a type attribute once you clicked save, and the templates were very different. So though, you get the data binding, if need a new template in there, you will have to recompile.