Ответ 1
РЕДАКТИРОВАТЬ: Полностью и полностью меняя свой ответ и отмечая это как "Community Wiki" (что означает отсутствие очков для меня), поскольку я был совершенно не прав, когда я ответил на это
Как пояснил @Jonah ниже, вот действительно хорошая статья о компиляции опций директив и использовании функции пересылки
Основная идея заключается в том, что функция компиляции должна возвращать функцию связывания. Вы можете использовать функцию пересылки, предусмотренную внутри функции связывания, чтобы взять клон переделанного элемента DOM, скомпилировать его и вставить туда, где нужно его вставить.
Вот лучший пример, который я вытащил из своего приклада в 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);
}
});
};
}
};
});