【问题标题】:Unable to access scope properties of parent directive in the child directive when parent scope is either true or isolated当父范围为真或孤立时,无法访问子指令中父指令的范围属性
【发布时间】:2016-08-27 02:55:18
【问题描述】:

我正在构建一个带有 parent 标签的自定义登录模块指令,其中包含 child 标签,例如 username & password。我在父作用域中定义了用户名和密码,并使用控制器函数进行通信。

    angular.module('sampleModule', [])
        .directive("parent",function(){return {
            restrict : 'E',
            transclude: true,
            scope: false,
            controller: function($scope, $element, $attrs){
                $scope.username = 'Init value';
                $scope.setUsername = function(name){
                    $scope.username = name;
                };
                $scope.getUsername = function(){
                    return $scope.username;
                }
            },
            link: function(scope, element, attrs){
                element.find('button').on('click', function(event){
                   alert('In Parent: '+ scope.username);
                });
            },
            template: '<div id="loginForm"><label>Parent: {{username}}</label><button>Check</button><br><br><ng-transclude></ng-transclude></div>'
        }})
        .directive("child",function(){return {
            restrict : 'E',
            require: '^parent',
            scope: true, //parent scope is available only when its true or false
            link: function(scope, element, attrs, parentCtrl){
                scope.$watch('username', function(newVal, oldVal){
                    if(newVal!=oldVal){
                        scope.setUsername(scope.username);
                    }
                });
            },
            template: '<input id="username" type="text" ng-model="username"><label>In Child: {{username}}</label>'
        }});

这是我第一次使用指令,我有以下疑问:

  1. 子指令能否继承父指令的独立作用域?

  2. 我希望封装模块数据(即应用程序其他地方不提供用户名和密码信息)。所以我正在考虑使包含用户名字段的父指令范围被隔离。但是,当我使此父范围属性在子范围中不可访问时。我该如何解决这个问题?

  3. 如果我将父指令范围设为 false,它的属性是否可以被包含它的控制器函数访问? 例如:username 是否可以在 SomeController 中使用?

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

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope angular-module


    【解决方案1】:

    将您的 getUsername 函数附加到 this 而不是范围:

    this.getUsername = functon(){....
    

    然后在您的子指令中,您可以通过以下方式访问它:

    parentCtrl.getUsername();
    

    要从父级访问子范围,您可以这样做:

    var child = element.find('child');
    var childScope = childElem.isolateScope();
    console.log(childScope.username);
    

    【讨论】:

    • 就像你提到的我将属性分配给 this 而不是父指令中的范围。而且我必须在父指令中使用 controllerAs 属性才能使用父模板中的控制器属性。 controllerAs: ctrl 和父 template: '{{ctrl.username}}'但是如何访问子模板中的控制器属性?! 控制器属性仅在子链接功能中可用,在模板中不可用
    • 只需将其附加到范围,因此在链接函数集scope.username = parentCtrl.getUsername(); 现在用户名在子模板中作为范围变量可用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    相关资源
    最近更新 更多