簡體   English   中英

AngularJS:ng-controller on指令不適用於指令中的transcluded元素

[英]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
                });

            };
        }
    };
})

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”,並且您的代碼可以通過此次調整按預期工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM