从
directive Angular docs,我看到编译函数有3个参数,其中之一是transclude。文档提供的唯一解释是:
transclude – A transclude linking function: function(scope,cloneLinkingFn).
我试图理解你将在克隆链接功能究竟做什么。我甚至不知道什么参数传入它。我发现one example有一个参数称为克隆,似乎是一个HTML元素。是否有其他参数可用?哪个HTML元素是这样的?我也在看可能使用transclude:’element’在我的指令。当使用’element’而不是true时,这些问题的答案是否改变?
我用简单的例子理解了transclusion,但我不能找到更复杂的例子,特别是transclude:’element’。我希望有人能提供一个更彻底的解释这一切。谢谢。
编辑:完全和完全改变我的答案,并标记为“社区Wiki”(意味着没有点我),因为我是完全错了当我回答这个
正如@Jonah在下面指出的,here is a really good article on the compile option of directives and using the transclusion function
基本思想是编译函数应该返回一个链接函数。您可以使用链接函数中提供的互斥函数获取转录的DOM元素的克隆,编译它,并将其插入到需要插入的位置。
Here is a better example I’ve pulled out of my butt on Plunker
编译函数的想法是它给你一个机会,在创建和调用链接函数之前,基于传递的属性,以编程方式改变DOM元素。
// a silly directive to repeat the items of a dictionary object. app.directive('keyValueRepeat',function ($compile){ return { transclude: true,scope: { data: '=',showDebug: '@' },compile: function(elem,attrs,transclude) { if(attrs.showDebug) { elem.append('<div class="debug">DEBUG ENABLED {{showDebug}}</div>'); } return function(scope,lElem,lAttrs) { var items = []; console.log(lElem); scope.$watch('data',function(data) { // remove old values from the tracking array // (see below) for(var i = items.length; i-- > 0;) { items[i].element.remove(); items[i].scope.$destroy(); items.splice(i,1); } //add new ones for(var key in data) { var val = data[key],childScope = scope.$new(),childElement = angular.element('<div></div>'); // for each item in our repeater,we're going to create it's // own scope and set the key and value properties on it. childScope.key = key; childScope.value = val; // do the transclusion. transclude(childScope,function(clone,innerScope) { //clone is a copy of the transcluded DOM element content. console.log(clone); // Because we're still inside the compile function of the directive,// we can alter the contents of each output item // based on an attribute passed. if(attrs.showDebug) { clone.prepend('<span class="debug">{{key}}: {{value}}</span>'); } //append the transcluded element. childElement.append($compile(clone)(innerScope)); }); // add the objects made to a tracking array. // so we can remove them later when we need to update. items.push({ element: childElement,scope: childScope }); lElem.append(childElement); } }); }; } }; });