我正在使用用户可以自定义的UI。我的UI模型基于JSON,但对于最终用户,他们希望以这样的方式对其进行自定义,即它们将在HTML中提供一些特定的标记。他们希望外部指令解析并处理它,而不是转发该内容。在实际场景中,外部指令在其模板中有一个表元素。内部标记只是告诉该指令需要显示JSON模型中提供的所有列。
为了更好地理解这一点,这是一个简化的例子:
正如您所看到的,在使用指令div
的{{1}}内部,有些内容不应该被转换为原样:
my-angular-dir1
我现在的要求是,能够在<I>
<br><div my-angular-dir1>
<br> <div my-angular-dir2="myData.node1"></div>
<br> <div my-angular-dir2="myData.node2"></div>
<br></div>
</I>
的链接函数(或其他地方)中获取<I><div my-angular-dir2="myData.node1"></div></I>
的内部标记,以便我可以使用该信息来决定需要什么由外部指令显示。
我怎样才能做到这一点?
答案 0 :(得分:0)
你可以使用这样的指令:
app.directive('outer', function() {
return {
restrict: 'E',
transclude: true,
link: function (scope, element, attrs, controller, transclude) {
transclude(scope, function(clone, scope) {
console.log(clone.html());
});
}
};
});
然后,如果您的HTML看起来像这样:
<outer>hello</outer>
你不会看到&#34;你好&#34;写入DOM,但您会看到它通过console.log
调用写入。在transclude
函数内部,您可以访问内部元素,然后您可以决定如何处理它们。
答案 1 :(得分:0)
这是fiddle
您需要使用手动转换并利用模板功能。 transclude:true遗憾的是在调用模板函数之前删除了内容,因此需要手动转换。
app.directive('myAngularDir1', function ($compile) {
return {
restrict: 'A',
template: function (tElement, tAttr) {
console.log('template: ' + tElement.html());
var content = tElement.children();
content.remove();
//process the content using a service (not shown)
var processedContent = angular.element('<div>ProcessedContent</div>');
//re-add to the directive
tElement.append(processedContent);
return '<div>Label: <input type="text" ng-model="myData.name">' + tElement.html() + '</div>'
},
replace: true,
compile: function (element, attr) {
console.log('compile: ' + element.html());
//we are going to need to do manual transclusion:
var transcludedContent = element.children();
element.children().remove();
return function (scope, element, attr, controller) {
// How to get the content like:
// <div my-angular-dir2="myData.node1"></div>
// that is in inside the current div in the HTML ??
console.log('link: html: ' + element.html());
//finish the manual transclusion
var newScope = scope.$parent.$new();
element.append($compile(transcludedContent)(newScope));
};
}
}
});