【问题标题】:inherit Angular parent directive attribute with isolate scope继承具有隔离范围的 Angular 父指令属性
【发布时间】:2015-09-21 19:22:46
【问题描述】:

我正在尝试从具有隔离范围的父自定义指令继承属性。在下面的示例中,我希望能够从 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 是可见的。我意识到我可以明确声明,但我宁愿了解如何正确地做到这一点。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    我不知道您为什么在 my-parent 上引用 parentInstance1parentInstance2,但 my-child 上的属性在 myParent$scope 中,因此您可以引用实际的 $scope.api 对象在myParent$scopemy-child 指令标记的属性中,然后在myChild 指令的隔离范围定义中引用该属性的名称。

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

    .. 然后在子指令中...

    app.directive('myChild', function () {    
    ...
    scope: {
       innerApi: '=?'
    }
    ...
    controller: function($scope) {
       $scope.innerApi  // <- accessible in the controller
    }
    

    这是simplified fiddle...

    【讨论】:

    • 是的,这就是要走的路。
    • 我已经尝试将此方法应用于我的代码,但它似乎与 ng-repeat(或可能 ng-transclude 包装 my-child> 应用)中断。
    • 我应该在 OP 中提到 具有 replace:true 和一个包含 指令的嵌入 div。
    • 您是否尝试过将 ng-repeat 放在模板中,以在每次迭代时实例化一个新的指令实例?请在您的回答中包含一个小提琴,以明确您遇到的特定问题。
    猜你喜欢
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 2015-09-05
    • 2019-10-21
    • 1970-01-01
    • 2015-07-09
    相关资源
    最近更新 更多