AngularJS指令转换部件绑定

apn*_*ing 5 angularjs angularjs-directive

我想在transcluded部分中使用指令,转换内容和调用指令的控制器方法:

<mydirective>
  <div ng-click='foo()'>
    click me
  </div>
</mydirective>


app.directive "mydirective", ->

  return {
    restrict:  'EACM',
    transclude: true
    template: "<div ng-transclude></div>"
    scope: { } #required: I use two way binding on some variable, but it's not the question here

    controller: [ '$scope', ($scope)->
      $scope.foo = -> console.log('foo')
    ]
  }
Run Code Online (Sandbox Code Playgroud)

plunkr在这里.

我该怎么办?

guy*_*abi 6

我有一个不同的答案,这不是一个黑客,我希望它会被接受..

我的plunkr进行现场演示

这是我对该指令的使用

<div custom-directive custom-name="{{name}}">      
  if transclude works fine you should see my name right here.. [{{customName}}]
</div>
Run Code Online (Sandbox Code Playgroud)

注意我customName在指令中使用,并为其指定一个值作为指令范围的一部分.

这是我的指令定义

angular.module('guy').directive('customDirective', function($compile, $timeout){
    return {
      template : '<div class="custom-template">This is custom template with [{{customName}}]. below should be appended content with binding to isolated scope using the transclude function.. wait 2 seconds to see that binding works</div>',
      restrict: 'AC',
      transclude: true, 
      scope : {
        customName : '@'
      }, 
      link : function postLink( scope, element, attrs, dummy, transcludeFn ){
          transcludeFn( scope, function(clone, innerScope ){
             var compiled = $compile(clone)(scope);
             element.append(compiled);
          });

         $timeout( function(){

            scope.customName = 'this stuff works!!!';

          }, 2000);
      }
    }
  });
Run Code Online (Sandbox Code Playgroud)

请注意,我将在2秒后更改范围上的值,以便显示绑定工作.

在网上阅读了很多内容后,我理解了以下内容:

  • ng-transclude指令是转换的默认实现,可以由用户根据用例重新定义
  • 重新定义转换意味着angular将在每个上使用您的定义 $digest
  • 默认情况下 - 转换创建一个新的范围,它不是孤立范围的子节点,而是兄弟节点(因此黑客工作).如果重新定义了转换过程,则可以在编译转换内容时选择使用哪个范围. - 即使新范围是STILL创建的,它似乎
  • transclude函数没有足够的文档.我甚至没有在文档中找到它.我在另一个SO答案中找到了它