如何将transcluded元素的scope属性绑定到父级



我正在尝试创建一个可重用的父容器指令。我想要的是以下内容:

<parent title="Parent title">
    <child></child>
</parent>

其中我可以让子元素更改父元素作用域中的值。

我尝试了如下绑定(请参见此小提琴):

myApp.directive('parent', function() {
    return {
        scope: {'title': '@'},
        transclude: true,
        // Manually transclude so we set parent scope to be this scope.
        link: function(scope, element, attrs, ctrl, transclude) {
            transclude(scope.$new(), function(content) {
                element.append(content);
            });
        },
        restrict: 'EA',
        template: '<div><b>PARENT:</b> {{title}}</div>',
        controller: function($scope) {
            $scope.inherited = true;
            $scope.$watch('inherited', function(newValue, oldValue) {
                if(!newValue) {
                    console.log('Parent: inherited switched');
                }
            });
        }
    }
});
myApp.directive('child', function() {
    return {
        restrict: 'EA',
        scope:{
            inherited: '='
        },
        template: '<div><b>Child:</b> inherited attribute = {{inherited}}</div>',
        controller: function($scope) {
            // Why is inherited not bound to parent here?
            console.log($scope.inherited);
            // It obviously exists in the parent...
            console.log($scope.$parent.inherited);
        }
    }
});

根据我对API的理解,使用inherited: '='设置对象哈希范围应该绑定到父属性,但正如您在fiddle中看到的,它没有。

我有两个问题:

  1. 为什么inherited没有绑定到父属性
  2. 我如何实现此消息传递

注意事项:

  • 我宁愿不使用require: '^parent',因为这会导致子容器对父容器的依赖性相当强(我可能想创建一些可能的父容器和一些子指令并进行混合匹配)
  • 我绝对不会在child指令中使用link来爬到$parent。这是一个黑客攻击,通常对深度嵌套的指令不起作用
  • 我愿意在家长身上使用一些技巧

感谢您的指导。

您可以执行以下操作之一:

<child inherited="inherited"></child>

您实际传入继承属性的位置,因为这是在执行时它所要查找的

scope:{
        inherited: '='
    },

或者你可以做:

myApp.directive('child', function() {
return {
    restrict: 'EA',
    scope: false,

以便它使用其父级的作用域。

无论哪种方式,您都可能遇到一些绑定到基元的问题。通过创建继承的对象,传递对象,并在需要显示对象时显示对象属性,您可能会省去很多麻烦:

JS:

$scope.inherited = {is: true};

HTML:

{{inherited.is}}

但随后继续绕过整个物体。

http://jsfiddle.net/GQX9z/1/

最新更新