这里 是我的剧本:
angular.module('MyApp',[])
.directive('mySalutation',function(){
return {
restrict:'E',
scope:true,
replace:true,
transclude:true,
template:'<div>Hello<div ng-transclude></div></div>',
link:function($scope,$element,$attrs){
}
};
})
.controller('SalutationController',['$scope',function($scope){
$scope.target = "StackOverflow";
}])
和HTML:
<body ng-app="MyApp">
<my-salutation ng-controller="SalutationController">
<strong>{{target}}</strong>
</my-salutation>
</body>
问题是,什么时候 SalutationController
适用于 my-salutation
指示, $scope.target
不可见 换了元素。但是如果我放了 ng-controller
上 <body>
或者 <strong>
元素,它的工作原理。如 文档 说, ng-controller
创造新的范围。
1)问题是 ng-transclude
的范围是 兄弟 你的指令的范围。当你把它 ng-controller
到父元素,创建范围 ng-controller
是你的指令和。的父范围 ng-transclude
。由于范围继承,transcluded元素能够绑定 {{target}}
正确。
2)您可以使用自定义转换来自己绑定范围
.directive('mySalutation',function(){
return {
restrict:'E',
scope:true,
replace:true,
transclude:true,
template:'<div>Hello<div class="transclude"></div></div>',
compile: function (element, attr, linker) {
return function (scope, element, attr) {
linker(scope, function(clone){
element.find(".transclude").append(clone); // add to DOM
});
};
}
};
})
DEMO
或者在链接函数中使用transclude函数:
.directive('mySalutation',function(){
return {
restrict:'E',
scope:true,
replace:true,
transclude:true,
template:'<div>Hello<div class="transclude"></div></div>',
link: function (scope, element, attr,controller, linker) {
linker(scope, function(clone){
element.find(".transclude").append(clone); // add to DOM
});
}
};
})
DEMO
要使指令和控制器具有相同的作用域,您可以手动调用transcludeFn:
angular.module('MyApp',[])
.directive('mySalutation',function(){
return {
restrict:'E',
scope:true,
replace:true,
transclude:true,
template:'<div>Hello<div class="trans"></div></div>',
link:function(scope, tElement, iAttrs, controller, transcludeFn){
console.log(scope.$id);
transcludeFn(scope, function cloneConnectFn(cElement) {
tElement.after(cElement);
});
}
};
})
.controller('SalutationController',['$scope',function($scope){
console.log($scope.$id);
$scope.target = "StackOverflow";
}]);
普拉克
您可以看到每次都会注销“003”,并且您的代码可以通过此次调整按预期工作。