让我们说在我的HTML中我有这样的东西:
<tabcontent></tabcontent>
然后这个指令的javascript是这样的:
tabsApp.directive('tabcontent', function(){
var myObj = {
priority:0,
template:'<div></div>',
replace: true,
controller: 'TabCtrl',
transclude: false,
restrict: 'E',
scope: false,
compile: function (element, attrs){
return function (parentScope, instanceEle){
parentScope.$watch('type', function(val) {
element.html('<div '+val+'></div>');
});
}
$compile(parentScope);
},
link: function postLink(scope, iElement, iAttrs){}
};
return myObj;
});
正确解析HTML,并在控制器JS中找到type的值。
so <tabcontent></tabcontent> is replaced with <div recipe></div> for example..
(那部分确实发生了)
所以我也有食谱指令:
tabsApp.directive('recipe', function(){
var myObj = {
priority:0,
template:'<div>TESTING</div>',
replace: true,
controller: 'TabCtrl',
transclude: false,
restrict: 'E',
scope: false,
compile: function (element, attrs){
return {
pre: function preLink(scope, iElement, iAttrs, controller){},
post: function postLink(scope, iElement, iAttrs, controller){}
}
},
link: function postLink(scope, iElement, iAttrs){}
};
return myObj;
});
这显然非常简单,仅用于测试。但是配方指令没有被处理......
这是怎么回事?
答案 0 :(得分:19)
你需要改变两件事:
recipe
指令不得限于 E (元素)。如果要生成<div recipe></div>
之类的指令,则必须至少将 A (属性)添加到指令配置的restrict
属性中:
app.directive('recipe', function() {
return {
restrict: 'E',
...
您需要在'watch'之后编译tabcontent
指令的HTML内容:
app.directive('tabcontent', function($compile){
return {
...
link: function (scope, iElement, iAttrs) {
scope.$watch('type', function(val) {
iElement.html('<div '+val+'></div>');
$compile(iElement.contents())(scope);
});
}
...
jsFiddle :http://jsfiddle.net/bmleite/n2BXp/