0

I want to access bindings in a transclude block, here a litte example:

<datagetter>
  <dataviewer data="$ctrl.data"></dataviewer>
</datagetter>

The datagetter component get some data via service and store it in a local variable e.g. this.data ( $ctrl.data in tempalte) - now i want to acces this data in the component that is set in the transclide block "dataviewer".

To solve this i read this articles, who come close to my problem:

Passing a binding to transcluded scope in component

AngularJS - access directive scope from transclude scope

I know i can use require to get the parentconroller in the childcomponent but this is not an option because i want to stay generic, for example it could be another "dataviewer" that takes the same data from "datagetter", also it should be used in a scenario where the "dataviwer" gets data from another datagetter.

is there a suitable solution for my needs? any help is appreciated

enno.void
  • 6,242
  • 4
  • 25
  • 42

1 Answers1

1

You need to do manual transclution, that's what I did in a similar situation. Anglers default transclution won't work, since it creates a new scope.

<datagetter>
  <dataviewer data="$ctrl.data"></dataviewer>
</datagetter>

/** * Parent component */

angular.module("app").component("datagetter", function() {
    constructor() {
        return {
            restrict: 'E',
            replace: true,
            template: "<div transclude-extended></div>",
            transclude: true,
            bindToController: true,
            controller: function () {
                var ctrl = this;
                    ctrl.data = 'This is sample data.';
            }
        };
    }
});

/** * Transclude Extended Directive */

angular.module("app").directive("transcludeExtended", function(){
    constructor() {
        return {
            link: function ($scope, $element, $attrs, controller, $transclude) {
                var innerScope = $scope.$new();
                $transclude(innerScope, function (clone) {
                    $element.empty();
                    $element.append(clone);
                    $element.on('$destroy', function () {
                        innerScope.$destroy();
                    });
                });
            }
        }
    };
});

transcludeExtended is the manual way of doing the translation, instead of ng-transclude

Reference: https://github.com/angular/angular.js/issues/1809