簡體   English   中英

AngularJS 使用 ng-repeat 在指令中嵌入范圍

[英]AngularJS transclude scope in directive with ng-repeat

我的目標是有一個指令,我給它內容,它重復 X 次。 就像 ng-repeat 一樣,只有我想將它包裝在其他功能中,例如限制切換和嵌入內容之外的額外元素。

出於某種原因,無論我嘗試什么,嵌入都無法訪問指令隔離范圍。

我在link使用了transclude函數,有幾種變體,但無濟於事。 這是一個演示:

這是代碼的要點:

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函數的內容應該處理它。 知道我能做什么嗎?

transclude:true嵌入內容,同時保留對內容被嵌入的范圍的引用(在我們的例子中, repeat-contents將嵌入<other-directive other-item="item"></other-directive>同時保留一個對外部作用域的引用。 item未在外部作用域中定義,並且您的隔離作用域定義item的事實與外部作用域無關。

如果您只想嵌入模板而不保留對其原始范圍的引用,則可以使用以下指令代替ng-transclude 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM