我正在构建一个自定义登录模块指令,其父标签包含子标签,如用户名和密码。我已经在父范围中定义了用户名和密码,并使用控制器功能进行通信。
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>'
}});
这是我第一次使用指令,我有以下疑问:
子指令可以从父指令的隔离范围继承吗?
我希望封装模块数据(即应用程序其他地方不提供用户名和密码信息)。所以我正在考虑使包含用户名字段的父指令范围被隔离。但是,当我使此父范围属性在子范围中不可访问时。我该如何解决?
如果我将父指令范围设置为false,它的属性是否可以被包含它的控制器函数访问?例如:用户名在SomeController中是否可用?
<div ng-controller="SomeController"> <parent> <child></child> </parent> </div>