AngularJS : ngRepeat in Directive with transcluded content

337 views Asked by At

I am trying to pass an array of objects to a directive, use ngRepeat inside of the directive to output the passed items in the transcluded html. It is essentially the same issue discussed here.

I tried some different ways, using the compile and link function but I guess I can't wrap my mind around the scoping. The suggested solution from petebacondarwin - here does work, but I need (want) to pass the array to the directive.

Here is my current Version - Plunker

Directive

(function() {
  "use strict";

  function MyDirective() {
    return {
      restrict: "E",
      scope: {
        items: "="
      },
      link: function link(scope, element, attrs) {
        var children = element.children();

        var template = angular.element('<div class="item" ng-repeat="item in items"></div>');
        template.append(children);

        var wrapper = angular.element('<div class="list"></div>');
        wrapper.append(template);

        element.html('');
        element.append(wrapper);
      }
    };
  }

  angular
    .module("app.MyDirective", [])
    .directive("myDirective", [MyDirective]);

}());

html

<my-directive items="main.items">
  <h1>{{item.title}}</h1>
  <p>{{item.content}}</p>
</my-directive>

thanks

1

There are 1 answers

0
Michael On BEST ANSWER

The code inside the directive is not compilated and thus it is not "visible" to Angular. This is caused by the fact that the code is not transcluded, but it's removed and replaced in the directive.

In order to "make it visible" to Angular, you should add this line of code at the end of link:

$compile(wrapper)(scope);

This take the new code wrapper, compiles it and link it to the scope

Updated plunkr:

http://plnkr.co/edit/9w7m4m4Uo0bShokz9uRR?p=preview