Question

I have a situation where I have to create a container directive with some bells and whistles.. and then I have a list of directives that can be wrapped into that container directive.

Something like this:

<the-container foo="bell" bar="whistle">

    <some-directive></some-directive>

</the-container>


<the-container foo="potato" bar="tomato">

    <some-other-directive></some-other-directive>

</the-container>

Is there any way in which I can make <some-directive> and <some-other-directive> aware of the foo and/or bar attributes values of the directive they are transcluded in?

Basic theContainer directive

.directive("theContainer", function() {
    return {
        restrict: "E",
        replace: true,
        transclude: true,
        scope: true,
        templateUrl: "theContainer.html",
        compile: function(element, attrs) {
            return function(scope, element, attrs) {
                scope.containerAttrs = {
                    foo: attrs.foo,
                    bar: attrs.bar
                };
            };
        }
    }
});

Let's presume that these two directives have different and unrelated function all together

someDirective

.directive("someDirective", function() {
    return {
        restrict: "E",
        scope: true,
        templateUrl: "someDirective.html",
        controller: function($scope, $element, $attrs) {},
        compile: function(element, attrs) {
            return function(scope, element, attrs) {
                // I need the value from theContainer foo and bar here
                // or anywhere in this directive for starters
                foo = 'bells';
                bar = 'whistles';
            };
        }
    }
});

someOtherDirective

.directive("someOtherDirective", function() {
    return {
        restrict: "E",
        scope: true,
        templateUrl: "someOtherDirective.html",
        controller: function($scope, $element, $attrs) {
            // I need the value from theContainer foo and bar here
            // or anywhere in this directive for starters
            foo = 'potato';
            bar = 'tomato';
        }
    }
});
Was it helpful?

Solution

Scopes in angular by default inherit from parent scope. Unfortunately, with angular default transclusion, there is no child/parent relationship between container and transcluded content.

You could try custom transclusion.

compile: function(element, attrs, linker) {
      return function(scope, element, attrs) {
        scope.containerAttrs = {
          foo: attrs.foo,
          bar: attrs.bar
        };
        linker(scope, function(clone) { //bind scope anyway you want
          element.append(clone); // add to DOM anywhere you want
        });
      };
}

Note: remember to remove ng-transclude in your template when you do custom transclusion,

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top