0

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.

    2 Answers 2

    0

    Doing this with ngTransclude is a bit challenge here, however I can provide you an alternative here Plnkr, if this is what you need!

    To make div nested you need to manually find the child and append another element to it.
    HTML

    <div ng-controller="mainController"> <hero-list data="heros"> <div ng-class='number'>Hero {{number}}</div> </hero-list> </div> 

    Directive(js)

    angular.module("app").directive("heroList", function(){ return { transclude: 'element', link: function(scope, el, attrs, ctrl, transclude) { var heros = scope.$eval(attrs.data); heros.forEach(function(each,idx) { transclude(function(transEl, transScope) { transScope.number = each.number; if(idx===0) { el.parent().append(transEl); } else { el.parent().find("div").append(transEl); } }); }); } } }); 
      -1

      In your second example, you are passing an object instead of a number in your hero directive, so you need to use model: "=" instead of model: "@". Here is a working sample.

      1
      • But it appends elements under the other. I want to append as nested
        – barteloma
        CommentedFeb 25, 2017 at 9:17

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.