使用隔离范围继承Angular父指令属性

时间:2015-09-21 19:22:46

标签: angularjs

我试图从具有隔离范围的父自定义指令继承属性。在下面的示例中,我希望能够从myChild控制器或链接函数访问myParent上的api属性。我的最终目标是注入一个api实例,可以由子视图和视图控制器访问。

<my-parent api="parentInstance1">
    <my-child ng-repeat="field in ::data"
        ng-attr-src="{{field.src||undefined}}"
    </my-child>        
</my-parent>

<my-parent api="parentInstance2">
    <my-child ng-repeat="field in ::data"
        ng-attr-src="{{field.src||undefined}}"
    </my-child>
</my-parent>

这两个指令的简化版本如下所示

app.directive('myParent', function () {
    return {
        transclude: true,
        restrict: "E",
        scope: {
            api: '=?'
        },
        template: '...',
        controller: function ($scope, $attrs ) {

            // foo is injected from a factory instance
            function foo ( ) {

            }

            $scope.api = {
                foo: foo
            }
        },
        link: function ($scope, $element, $attr) {

        }
    }
});

app.directive('myChild', function () {
    return {
        require: "^myParent",
        restrict: "E",
        scope: {
            api: '=?'                
        },
        template: "...",
        controller: function ( $scope ) {
            // I want to access $scope.api in link or controller            
        },
        link: function ($scope, $element, $attr) {
            // I want to access $scope.api in link or controller
        }
    }
});

我无法从子指令访问$ scope.api,但$ scope.parentInstance1和$ scope.parentInstance2是可见的。我意识到我可以明确地声明,但我更应该理解如何正确地做到这一点。

1 个答案:

答案 0 :(得分:1)

我不知道您在parentInstance1上引用parentInstance2my-parent的原因,但my-child上的属性位于myParent&#39; s {{ 1}}这样您就可以在$scope指令标记的属性中引用$scope.api&#39; s myParent上的实际$scope对象,然后引用该名称my-child指令的隔离范围定义中的属性。

myChild

..然后在儿童指令......

<my-child inner-api="api"></my-child>

继承人simplified fiddle ...

相关问题