jjzjj

javascript - Angular : ng-controller on directive does not work on transcluded elements within directive

coder 2024-05-14 原文

Here是我的脚本:

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>元素,它的工作原理。作为docs说,ng-controller创建新的范围。

  • 谁能解释一下,在这种情况下,该范围和指令的范围如何相互干扰?

  • 如何将 Controller 放在指令上?任何提示将不胜感激。

最佳答案

1) 问题是 ng-transclude 的范围是指令的 sibling 范围。当您将 ng-controller 放入父元素时,由 ng-controller 创建的作用域是您的指令和 ng-transclude 的父作用域>。由于范围继承,嵌入的元素能够正确绑定(bind) {{target}}

2) 您可以使用自定义嵌入来自己绑定(bind)作用域

.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

关于javascript - Angular : ng-controller on directive does not work on transcluded elements within directive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22575424/

有关javascript - Angular : ng-controller on directive does not work on transcluded elements within directive的更多相关文章

随机推荐