AngularJS: передача значения атрибута из одной директивы в включенную

У меня есть ситуация, когда мне нужно создать директиву контейнера с некоторыми прибамбасами... и затем у меня есть список директив, которые можно обернуть в эту директиву контейнера.

Что-то вроде этого:

<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>

Есть ли способ, которым я могу сделать <some-directive> и <some-other-directive> осведомленными о значениях атрибутов foo и/или bar директивы, в которую они включены?

Основная директива theContainer

.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
                };
            };
        }
    }
});

Давайте предположим, что эти две директивы вместе имеют разные и несвязанные функции.

какая-то директива

.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';
            };
        }
    }
});

какая-то другая директива

.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';
        }
    }
});

person GRowing    schedule 02.03.2014    source источник
comment
Узнайте больше о наследовании $scope в AngularJS. Возможно, этот пост поможет вам stackoverflow .com/questions/15622863/   -  person Tome Pejoski    schedule 02.03.2014
comment
Спасибо за совет :) Кажется, я тоже это читал.   -  person GRowing    schedule 02.03.2014


Ответы (1)


Области в angular по умолчанию наследуются от родительской области. К сожалению, при включении angular по умолчанию между контейнером и включенным содержимым нет отношения дочерний/родительский.

Вы можете попробовать пользовательское включение.

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
        });
      };
}

Примечание: не забудьте удалить ng-transclude из своего шаблона, когда будете выполнять пользовательское включение,

ДЕМО

person Khanh TO    schedule 02.03.2014
comment
Это здорово спасибо! Я могу легко настроить его на то, что мне нужно. Я знаю, что ng-transclude создает родственную область, я не знал, как это обойти. Это потрясающе. - person GRowing; 02.03.2014