I've been trying to create a directive that takes the content of the element and wraps it with an ng-repeat. The trick is that the expressions in the content of the element have to be linked with the isolated scope of the directive (so I can't use ng-transclude).
I found a solution that seemed perfect: https://github.com/angular/angular.js/issues/7874#issuecomment-46410994 But it doesn't work with an isolated scope which isn't satisfactory, I require an isolated scope in order not to pollute the parent scope.
In the following plnkr, you can try commenting line 10, and it will work. http://plnkr.co/edit/B72H9Sd5Cs1Qc8GoTRGF
<test>
<h3>- number: {{item}}</h3>
</test>
app.directive('test', function(){
return {
restrict: 'E',
scope: {}, // try commenting this line
compile: function compile(tElement, tAttrs, tTransclude) {
var children = tElement.children();
var template = angular.element('<div ng-repeat="item in collection"></div>');
template.append(children);
tElement.html('');
tElement.append(template);
return function(scope, iElement, iAttrs, controller) {
scope.collection = [1, 2, 3, 4, 5];
};
}
};
});
What I would like is the
- number: {{item}}
to be repeated for each collection item and the {{item}} expression to be linked with the isolated scope.I don't understand the behavior. It seems to me like the {{item}} expression should be linked to the directive's scope (through the ng-repeat). Instead, it's linked with the parent scope.
Could somebody please help me understand and fix this?
Thank you.
linkfunction for your directive, thus it is running after the compile phase. Adding AngularJS directives toelementin the link phase won't compile them. So you manually need to compile them using$compile.templatefunction you defined is called before the compile phase, thus thedata-ng-repeatdirective is compiled later in the compile phase, unlike when adding it in the linking phase.