I'm trying to create directives dynamically inside an ng-repeat. I have a directive-writer
that creates a number of other directives but the directive-writer
doesn't seem to output the directive attributes. So the second set of directives are never rendered.
See this Plunker for a full demo.
In short I have this directive tag:
<div ng-repeat="dir in directives" directive-writer
directive-text="{{ dir.text }}" directive-type="{{ dir.directive }}"></div>
Scope data:
$scope.directives = [
{ directive: 'one', text: 'I am One' },
{ directive: 'two', text: 'I am Two' },
{ directive: 'three', text: 'I am Three' }
];
Directive definition:
.directive('directiveWriter', function() {
return {
restrict: 'A',
compile: function(tElement, tAttrs) {
tElement.html('<div say="' + tAttrs.directiveText + '" '
+ tAttrs.directiveType + '>' + tAttrs.directiveType + '</div>');
}
};
And 3 more directives all like this one:
.directive('one', function() {
return {
restrict: 'A',
replace: true,
template: '<h3 class="one"></h3>',
compile: function(tElement, tAttrs) {
tElement.text('One says, ' + tAttrs.say);
}
};
The problem is the directiveWriter
doesn't write out the tAttrs.directiveType
value as an attribute only as text...
So the rendered HTML is:
<div say="I am One" {{ dir.directive }} class="ng-binding">one</div>
Where "three" is rendered inside the div as text no problem but is never rendered as an attribute.
I don't understand:
- Why the text "three" can be bound inside the div as text but not as an attribute.
- Why the class is set to "ng-binding".
I modified your example. Now it works. You should use $compile.
See this
One of the issues is order that attributes get resolved into html. They are available in scope earlier in the cycle Here's one way you can do it:
HTML:
Directive:
DEMO