AngularJS使用ng-repeat在指令中转换范围

时间:2016-05-31 16:01:26

标签: javascript angularjs angularjs-directive angularjs-ng-transclude

我的目标是有一个指令,我给它内容,并重复它们X次。就像ng-repeat一样,只有我想把它包装在其他功能中,例如限制切换和转换内容之外的额外元素。

出于某种原因,无论我尝试什么,转换都无法访问指令隔离范围。

我在transclude内使用了link功能,在几个版本中,无济于事。这是一个演示:

以下是代码的要点:

app.directive('repeatContents', function() {
  return {
    scope: {
      items: '=repeatContents',
      limit: '=repeatLimit'
    },
    transclude: true,
    template: '<div ng-repeat="item in items">' +
                  '<em>Outside transclude: {{item}}</em><br />' +
                  '<ng-transclude></ng-transclude>' +
              '</div>',
    link: function(scope, el, attrs, ctrl, transclude) {
      transclude(scope, function(clone, scope) {
        el.append(clone);
      });
    }
  }
});

如果你看一下plunkr,你会看到在翻译{{item}}之外,但不在里面。无论link函数的内容应该如何处理它。知道我能做什么吗?

1 个答案:

答案 0 :(得分:1)

transclude:true转换内容,同时保留对内容被转换范围的引用(在我们的示例中,repeat-contents将转换<other-directive other-item="item"></other-directive>,同时保留对外部范围的引用。 item未在外部范围中定义,并且您的隔离范围定义item与外部范围无关。

如果您只想在不保留对其原始范围的引用的情况下转换模板,则可以使用以下模式而不是ng-transclude

app.directive('customTransclude', function(){
    return {
        link: function(scope, element, attrs, ctrls, transcludeFn){
            if(!transcludeFn){
                throw 'Illegal use of custom-transclude directive! No parent directive that requires transclusion was found';
            }

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

然后在repeat-contents指令的模板中,您可以像这样使用它:

<div ng-repeat="item in items">
    <em>Outside transclude: {{item}}</em><br/>
    <custom-transclude></custom-transclude>
</div>
相关问题