繁体   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