Jack Jack - 5 months ago 34
AngularJS Question

AngularJS directive dynamic templates

Sorry, maybe it's stupid question but i'm still learning.

I'm trying to make directive with differtent templates based on scope value.

This is what i done so far which i don't know why doesn't work http://jsbin.com/mibeyotu/1/edit

Html element:

<data-type content-attr="test1"></data-type>


Directive:

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

app.directive('dataType', function ($compile) {

var testTemplate1 = '<h1>Test1</h1>';
var testTemplate2 = '<h1>Test2</h1>';
var testTemplate3 = '<h1>Test3</h1>';

var getTemplate = function(contentType){

var template = '';

switch(contentType){
case 'test1':
template = testTemplate1;
break;
case 'test2':
template = testTemplate2;
break;
case 'test3':
template = testTemplate3;
break;
}

return template;
};

var linker = function(scope, element, attrs){
element.html(getTemplate(scope.content)).show();
$compile(element.contents())(scope);
};

return {
restrict: "E",
replace: true,
link: linker,
scope: {
content:'='
}
};
});

Answer

1) You are passing content as attribute in your html. Try this:

element.html(getTemplate(attrs.content)).show();

instead of:

element.html(getTemplate(scope.content)).show();

2) data part of directive is getting compiled so you should use something else. Instead of data-type, e.g. datan-type.

Here is the link:

http://jsbin.com/mibeyotu/6/edit