如何使用指令动态更改模板? [英] How to use a directive to dynamically change a template?
本文介绍了如何使用指令动态更改模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个指令
angular.module('starter.directive', [])
.directive('answer', ['Helper', function (Helper) {
return {
require: "logic",
link: function (scope, element, attrs, logicCtrl) {
var htm = '';
if(logicCtrl.test == 'a') {
htm = '<p>a</p>'
}
if(logicCtrl.test == 'b') {
htm = '<p>b</p>'
}
},
template: '' // somehow use htm here
}
}]);
我正在尝试将 htm
用于 template
,
I'm trying to use the htm
for the template
,
有什么想法吗?
推荐答案
你可以将 htm
放入指令的 scope
并在模板中使用它.
You can just put htm
into scope
of directive and use it inside template.
angular.module('starter.directive', [])
.directive('answer', ['Helper', function (Helper) {
return {
require: "logic",
link: function (scope, element, attrs, logicCtrl) {
scope.htm = '';
if(logicCtrl.test == 'a') {
scope.htm = '<p>a</p>'
}
if(logicCtrl.test == 'b') {
scope.htm = '<p>b</p>'
}
},
template: '{{htm}}' // somehow use htm here
}
}]);
更新
要将 html 字符串编译为模板,您需要使用 $compile 服务,只是可能的例子:
UPDATE
To compile html strings into template you need to use $compile service, just possible example:
angular.module('starter.directive', [])
.directive('answer', ['Helper', function (Helper) {
return {
require: "logic",
link: function (scope, element, attrs, logicCtrl) {
var htm = '';
if(logicCtrl.test == 'a') {
htm = '<p>a</p>'
}
if(logicCtrl.test == 'b') {
htm = '<p>b</p>'
}
var el = angular.element(htm);
compile(el.contents())(scope);
element.replaceWith(el);
}
}
}]);
这篇关于如何使用指令动态更改模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文