vlio20 vlio20 - 6 months ago 34
AngularJS Question

Angular: calling transclude directive function from within the transcluded component

I want to create a component which will have a transcluded part, here is an example:

http://jsfiddle.net/vp2dnj65/1/

As you can see when clicking the do button nothing happens.

Is there any way to run transcluded controller function from a component which is placed within the transcluded part.

Here is the HTML:

<panel> // trans is the name of the controller of panel
<button ng-click="trans.do()">do</button> //transcluded part
</panel>

Answer

you can achieve that if you manually transclude the element and attach the scope function to it:

compile: function(tElement, tAttrs) {
  var parentElement = tElement.parent();
  return function(scope, element, attrs, ctrl, transclude) {
    transclude(scope.$new(), function(clone) {
      clone.bind('click', function() {
        scope.trans.do();
      })
      parentElement.append(clone);
    });
  };
}

as shown in this tutorial. see also this fiddle.