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

标签 javascript angularjs angularjs-directive transclusion

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/

相关文章:

AngularJS : ng-repeat's compile and link functions

javascript - Highcharts 使用分组值动态更新图例

javascript - AngularJS:何时在 'scroll' 事件中使用 $apply

angularjs - Angular 父/子指令的执行顺序

angularjs - Angular JS触摸和滑动

angularjs - Sails/Angular 跨源请求被阻止

javascript - 如何重新注册动态加载的 Angular 模板指令

Javascript获取同一类的索引在html页面中重复多次

javascript - 你如何使用 jquery sortable 对所有表格行中的表格单元格进行排序?

javascript - 从 session 存储中打开折叠