我想创建一个自定义指令,该指令将其他自定义指令动态插入到包装器的模板中。但是我找不到合适的方法。到目前为止,我已经提出了以下解决方案,不幸的是不起作用。
angular.module('myApp', [])
.directive('contentDir', function () {
return {
restrict: 'E',
replace: true,
template: '<div><b>Content is here</b></div>'
};
})
.directive('wrapperDir', function () {
return {
restrict: 'E',
scope: {
htmlContent: '@htmlContent',
},
replace: true,
controller: function($scope, $sce){
$scope.sContent = $sce.trustAsHtml($scope.htmlContent);
},
template: '<div>This is a wrapper for the... <span ng-bind-html="sContent"></span>!</div>'
};
})
;
//.html
<wrapper-dir html-content="<content-dir></content-dir>"></wrapper-dir>
wrapper-dir 指令不生成 html。谁能解释一下我做错了什么以及正确的方法是什么?
你可以在wrapperDir上使用transclude,然后你可以在html上使用所需的内部html/指令:
.directive('wrapperDir', function () {
return {
restrict: 'E',
scope: {
},
replace: true,
transclude: true,
controller: function($scope, $sce){
},
template: '<div>This is a wrapper for the... <span ng-transclude></span>!</div>'
};
});
在 html:
<wrapper-dir><content-dir></content-dir></wrapper-dir>
$compile我在您的示例中使用了类似的代码:
yourApp.directive('compileBindedHtml', ['$compile', function($compile) {
return {
restrict: 'A', // only activate on element attribute
link: function(scope, elem, attrs) {
scope.$watch(attrs.compileBindedHtml, function(newValue, oldValue) {
if (newValue) {
elem.html(newValue);
$compile(elem.contents())(scope);
}
});
}
}
}]);
然后在代码中:
<div compile-binded-html="titleHtml"></div>
其中 titleHtml 是包含 html/angular 模板代码的变量。
在您的示例中,应该只缺少部分:
$compile(elem.contents())(scope);
编译元素的内容以解析角度模板并与范围绑定。
也许这会具体回答您的问题。
但是你不能像这样简单地将内容Dir包装在包装器Dir中:
.directive('wrapperDir', function () {
return {
...
template: '<div><span>This is a wrapper for the... </span><span><content-dir></content-dir></span><span>!</span></div>'
};
})
然后只需使用:
<wrapper-dir></wrapper-dir>