本文介绍了AngularJS 指令动态模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据范围值使用不同的模板制作指令.
I'm trying to make directive with differtent templates based on scope value.
这是我到目前为止所做的,但我不知道为什么不起作用 http://jsbin.com/mibeyotu/1/edit
This is what i done so far which i don't know why doesn't work http://jsbin.com/mibeyotu/1/edit
HTML 元素:
<data-type content-attr="test1"></data-type>
指令:
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:'='
}
};
});
推荐答案
1) 您将内容作为 html 中的属性传递.试试这个:
1) You are passing content as attribute in your html. Try this:
element.html(getTemplate(attrs.content)).show();
代替:
element.html(getTemplate(scope.content)).show();
2) 指令的数据部分正在编译,因此您应该使用其他内容.而不是数据类型,例如数据类型.
2) data part of directive is getting compiled so you should use something else. Instead of data-type, e.g. datan-type.
这是链接:
http://jsbin.com/mibeyotu/6/edit
这篇关于AngularJS 指令动态模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!