当父范围为真或隔离时,无法访问子指令中父指令的范围属性

时间:2016-05-02 10:58:50

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

我正在构建一个自定义登录模块指令,其标记包含标记,例如 username&密码。我在父作用域中定义了用户名和密码,并使用控制器功能进行通信。

    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 ,控制器功能是否可以访问其属性? 例如: SomeController 中是否可以使用 用户名

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

1 个答案:

答案 0 :(得分:0)

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

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

然后在您的子指令中,您可以使用以下命令访问它:

parentCtrl.getUsername();

要从父级访问子范围,您可以执行以下操作:

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