2

我正在构建一个自定义登录模块指令,其父标签包含标签,如用户名和密码。我已经在父范围中定义了用户名和密码,并使用控制器功能进行通信。

    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>
    
4

1 回答 1

0

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

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

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

parentCtrl.getUsername();

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

var child = element.find('child');
var childScope = childElem.isolateScope();
console.log(childScope.username);
于 2016-05-02T11:42:28.440 回答