Подтвердить что ты не робот

Доступ к родительскому охвату в директиве Transcluded

Я хотел бы получить доступ к области родительской директивы, но я не могу получить правильную комбинацию настроек. Возможно ли это, и это правильный подход?

Я действительно хочу избежать помещать что-то вроде SOME_CONST (что поможет мне сделать обновления DOM через поток управления) в MyCtrl

<div ng-controller="MyCtrl">
    <parent>
        <child></child>
    </parent>
</div>

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.obj = {prop:'foo'};
}

myApp.directive('parent', function() {
    return {
        scope: true,
        transclude: true,
        restrict: 'EA',
        template: '<div ng-transclude><h1>I\'m parent {{obj.prop}}<h1></div>',
        link: function(scope, elem, attrs) {
            scope.SOME_CONST = 'someConst';
        }
    }
});

myApp.directive('child', function() {
    return {
        restrict: 'EA',
        template: '<h1>I\'m child.... I want to access my parent\ stuff, but I can\'t.  I can access MyCtrlScope though, see <b>{{obj.prop}}</b></h1> how can I access the <b>SOME_CONST</b> value in my parent\ link function?  is this even a good idea? {{SOME_CONST}}.  I really don\'t want to put everything inside the MyCtrl',
    }
});

Смотрите скрипт

Спасибо

4b9b3361

Ответ 1

С transclude: true и scope: true директива parent создает две новые области: enter image description here

Область 004 является результатом scope: true, а область 005 является результатом transclude: true. Поскольку директива child не создает новую область действия, она использует transcluded scope 005. Как видно из диаграммы, нет пути из области видимости 005 в область 004 (кроме как через частное свойство $$ prevSibling, которое идет в противоположном направлении направление $$ nextSibling - но не используйте их.)

Решение @joakimbl, вероятно, лучше всего здесь, хотя я считаю, что более часто определять API на родительском директивном контроллере, а не определять свойства на this:

controller: function($scope) {
    $scope.SOME_CONST = 'someConst';
    this.getConst = function() {
       return $scope.SOME_CONST;
    }
}

Тогда в директиве child:

link:function(scope,element,attrs,parentCtrl){
    scope.SOME_CONST = parentCtrl.getConst();
},

Вот как работают директивы tabs и pane на домашней странице Angular (пример "Создать компоненты" ).

Ответ 2

Обычно способ доступа к переменной родительского объекта в директиве осуществляется посредством двунаправленного привязки (scope:{model:'=model'}- см. руководство по angular по директивам) в директивная конфигурация), но поскольку вы используете переключение, это не так прямолинейно. Если дочерняя директива всегда будет дочерней родительской директивой, вы можете настроить ее на требование родителя, а затем получить доступ к родительскому контроллеру в дочерней ссылке:

myApp.directive('parent', function() {
  return {
    scope: true,
    transclude: true,
    restrict: 'EA',
    template: '<div ng-transclude><h1>I\'m parent {{obj.prop}}<h1></div>',
    controller: function($scope) {
        $scope.SOME_CONST = 'someConst';
        this.SOME_CONST = $scope.SOME_CONST;
    }
  }
});

myApp.directive('child', function() {
  return {
    restrict: 'EA',
    require:'^parent',
    scope:true,
    link:function(scope,element,attrs,parentCtrl){
        scope.SOME_CONST = parentCtrl.SOME_CONST;
    },
    template: '<h1>I\'m child.... I want to access my parent\ stuff, but I can\'t.  I can access MyCtrlScope though, see <b>{{obj.prop}}</b></h1> how can I access the <b>SOME_CONST</b> value in my parent\ link function?  is this even a good idea? {{SOME_CONST}}.  I really don\'t want to put everything inside the MyCtrl',
  }
});

Смотрите это обновление: http://jsfiddle.net/uN2uv/

Ответ 3

У меня была такая же проблема и, наконец, она была решена с помощью руководства angular;)

Вкратце: вам нужно использовать контроллер директивы родительский и требовать, этот контроллер в дочерняя. Таким образом, вы можете получить свои родительские свойства.

См. https://docs.angularjs.org/guide/directive Глава: Создание директив, сообщающих

Я изменил свою скрипту, чтобы использовать контроллер, теперь вы можете получить доступ к своей константе: https://jsfiddle.net/bbrqdmt3/1/

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.obj = {prop:'foo'};
}

myApp.directive('parent', function() {
    return {
        scope: true,
        transclude: true,
        restrict: 'EA',
        template: '<div ng-transclude><h1>I\'m parent {{obj.prop}}<h1></div>',
        controller: function($scope) {
            this.getConst= function() {
                return 'someConst';
            }                        
        },
    }
});

myApp.directive('child', function() {
    return {
        restrict: 'EA',
        require : '^parent',
        link: function(scope, element, attrs, ctrl) {
            scope.value= ctrl.getConst();
        },
        template: '<h1>I\'m child.... I want to access my parent\ stuff, but I can\'t.  I can access MyCtrlScope though, see <b>{{obj.prop}}</b></h1> how can I access the <b>SOME_CONST</b> value in my parent\ link function?  is this even a good idea? {{value}}.  I really don\'t want to put everything inside the MyCtrl',
    }
});

Ответ 4

Там transclude fn в аргументах ссылки fn после контроллера.

myApp.directive('parent', function() {
  return {
    scope: true,
    transclude: true,
    restrict: 'EA',
    template: '<div><h1>I'm a parent header.</h1></div>',
    link: function (scope, el, attrs, ctrl, transclude) {

        transclude(scope, function (clone, scope) {
            element.append(clone); // <-- will transclude it own scope
        });

    },
    controller: function($scope) {
        $scope.parent = {
            binding: 'I\'m a parent binding'
        };
    }
  }
});

myApp.directive('child', function() {
  return {
    restrict: 'EA',
    require:'^parent',
    scope:true,
    link:function(scope,element,attrs,parentCtrl){

    },
    template: '<div>{{parent.binding}}</div>' // <-- has access to parent scope
  }
});