Angular transcluded directive as sibling scope incompatible with child directive's require: "^parent" setting

StackOverflow https://stackoverflow.com/questions/23647677

Вопрос

I'm having an issue with the way AngularJS handles transcluded scopes for directives. It is known that a transclude's scope is a sibling of its directive's scope, not a child. Shown here

However, I have a situation with a child directive:

 <div price-chart>
      <div volume-indicator></div>
 </div>

The priceChart directive has a transclude: true, template: "<div ng-transclude></div>" but the (transcluded) volumeIndicator requires the parent to be a priceChart, not the sibling.

function VolumeIndicatorDirective() {
    return {
        restrict: "EA",
        controller: "VolumeIndicatorController",
        require: ["^priceChart", "volumeIndicator"],
        compile: function compile(element, attrs, transclude) {
            return {
                pre: function preLink($scope, element, attrs, controllers) {
                    var priceChart = controllers[0];
                    var volumeIndicator = controllers[1];
                    priceChart.addIndicator(volumeIndicator);
                },
                post: angular.noop
            };
        }
    };
}

If Angular had a sibling selector for controllers that would solve the issue:

require: ["+priceChart", "volumeIndicator"],

However, this doesn't exist so what can I do?

As per comment from zeroflagL I tried element.parent().controller() to access the directive controller but it seems to get the nearest ng-controller specifically and skips over directive controllers.

Это было полезно?

Решение

According to the docs, require's '^' syntax will try to "locate the required controller by searching the element's parents". Scope prototypal inheritance doesn't play a role here, so your code should work as expected.

And indeed it does !

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top