[英]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.