首页 > 解决方案 > AngularJS Transcluded 指令的范围从其他指令捕获

问题描述

我得到了嵌入指令,例如“ aDirective ”和其他随机的“ bDirective ”指令。我的任务是:我想获得一个“ aDirective 的范围变量”并在“ bDirective ”中捕获它。

angular.module('myApp',[])
  .controller('bDirective',['$scope',function(scope){

    scope.getScopeVar = function () {

    // here I want to get aDirective - s 'someVar' variable
    scope.someVar;

        debugger;
    };
    scope.getScopeVar();
  }])
  .directive('aDirective',function(){
    return{
    scope:{},
    transclude:true,
    template:'<div>123</div>',
    link: function(scope, element, attrs, controller, transclude){
      scope.someVar = 'asd';

      transclude(scope, function (clone) {
        element.append(clone);
      });
    }
    };
});

有什么解决办法吗?问候尼克。

标签: angularjsangularjs-directivescopeangularjs-ng-transclude

解决方案


嵌套指令应该require是从顶部开始的指令。然后它可以接收它的控制器作为link函数参数(第四个)。

.directive('nestedDirective', function(){
 return {
   require: '^aDirective',
   link: function (scope, elements, attrs, aDirectiveController) {
     // access aDirectiveController's methods or properties
   }
 }
})

推荐阅读