[英]AngularJS : ng-controller on directive does not work on transcluded elements within directive
这是我的脚本:
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
对于$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
});
};
}
};
})
或者在链接函数中使用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
});
}
};
})
要使指令和控制器具有相同的范围,可以手动调用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”,并且您的代码可以通过此次调整按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.