I have a nested directive that has nested hierarchy.
angular.module("app", []);
angular.module("app").directive("hero", function () {
return {
restrict: "E",
template: "<div>Hero {{number}}</div> <div ng-transclude></div>",
scope: {
number: "@"
},
transclude: true,
link: function (scope) {
}
}
});
I can use it in html file like this:
<div ng-app="app">
<hero number="1">
<hero number="2">
<hero number="3"></hero>
</hero>
</hero>
</div>
This works here demo.
Now I want to do this dynamically, and my hero model items are in a controller:
angular.module("app").controller("mainController", function ($scope) {
$scope.heros = [
{ number: "1" },
{ number: "2" },
{ number: "3" },
]
});
And created a new <hero-list>
directive that compiles all <hero>
in controller model.
angular.module("app").directive("heroList", function ($compile) {
return {
restrict: "E",
scope: {
data: "="
},
link: function (scope, element) {
var temp;
angular.forEach(scope.data, function(item){
var tempScope = scope.$new(true);
tempScope.model = item;
var item = angular.element('<hero model="model"></hero>');
if(temp){
if(temp.children().length){
var k = temp.children().append(item)
temp=k;
}else
temp.append(item);
}else{
temp = item;
}
$compile(item)(tempScope);
});
element.append(temp);
}
}
});
I will use it like this but does not compile nested, it appends and compiles under one other:
<div ng-app="app">
<div ng-controller="mainController">
<hero-list data="heros"></hero-list>
</div>
</div>
Working (demo-2)
I think this is an advenced level problem.