Skip to content Skip to sidebar Skip to footer

Is It Possible To 'transclude' While Keeping The Scope Of The Directive In Angular?

Is possible to do the following in Angular?
Hello {{name}}! // I expect 'Hello

Solution 1:

That happened to you because you were too aggressive with the element.

You can do different things instead of replaceWith that will... replace the current element.

You can append it to the end, prepend it... pick one template element and insert it inside... Any DOM manipulation. For example:

app.directive('test', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@'
    },
    transclude: true,
    template: '<div class="test">This is test</div>',
    link: function(scope, element, attrs, ctrl, transclude) {
      transclude(scope, function(clone) {
        element.append(clone);
      });
    }
  };
});

Here I decided to put it after the element, so you could expect:

This is test
Hello Matei!
This is test
Hello David!

Notice I did not included ng-transclude on the template. It is not needed because you're doing that by hand.

So TL;DR;: Play with the element, don't just replace it, you can insert the transcluded html where you want it, just pick the right element, and call the right method on it.

For the sake of completeness here is another example: http://plnkr.co/edit/o2gkfxEUbxyD7QAOELT8?p=preview

Post a Comment for "Is It Possible To 'transclude' While Keeping The Scope Of The Directive In Angular?"