我遇到的问题可以在 http://jsfiddle.net/miketheanimal/2CcYp/13/ 看到这将我的问题减少到最低限度。
我有一个 Controller “main”,一个指令“outer”,它不包含的指令,以及一个指令“inner”。每个指令都有一个隔离范围和一个 Controller 。主 Controller 和指令 Controller 设置 $scope._name = '...' 所以我可以区分它们。
var module = angular.module('miketa', []);
function main ($scope) {
$scope._name = 'main' ;
} ;
module.directive('outer', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {},
template: '<div><div ng-transclude></div></div>',
controller: [ '$scope', function($scope) {
$scope._name = 'outer' ;
document.getElementById('opn').innerHTML = $scope.$parent._name ;
}]}});
module.directive('inner', function() {
return {
restrict: 'E',
replace: true,
scope: {},
template: '<div></div>',
controller: [ '$scope', function($scope) {
$scope._name = 'inner' ;
document.getElementById('ipn').innerHTML = $scope.$parent._name ;
}]}});
HTML 将它们嵌套为主 -> 外部 -> 内部。指令中的 Controller 函数复制它们的家长 范围名称(即,*$scope.$parent._name)到呈现的 HTML 中(对于直接操作 DOM 表示歉意,这是显示名称的最简单方法!)。
我希望外部显示来自 Controller 的名称(即“main”),这是确实的,我希望内部显示来自外部的名称(即,“外部”),而不是,相反,它也显示“主要”。
问题实际上表现出来,因为在实际代码中,我想在内部和外部范围之间进行绑定(bind),但内部最终绑定(bind)到主范围。
最佳答案
实际上,这不是错误,而是所需的行为。来自 docs on the $compile
service :
In a typical setup the widget creates an isolate scope, but the transclusion is not a child, but a sibling of the isolate scope. This makes it possible for the widget to have private state, and the transclusion to be bound to the parent (pre-isolate) scope.
另见:Why ng-transclude's scope is not a child of its directive's scope - if the directive has an isolated scope?
如果你真的需要让它工作忘记
ng-transclude
并做:var module = angular.module('miketa', []);
function main($scope) {
$scope._name = 'main';
};
module.directive('outer', function () {
return {
restrict: 'E',
replace: true,
scope: {},
template: '<div><inner></inner></div>',
controller: ['$scope', function ($scope) {
$scope._name = 'outer';
document.getElementById('opn').innerHTML = $scope.$parent._name;
}]
}
});
module.directive('inner', function () {
return {
restrict: 'E',
replace: true,
scope: {},
template: '<div></div>',
controller: ['$scope', function ($scope) {
$scope._name = 'inner';
document.getElementById('ipn').innerHTML = $scope.$parent._name;
}]
}
});
瞧!有用。
关于angularjs - 嵌套指令和父范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19026421/