2014-09-02 49 views
1

我想用angularjs創建一個表格模板。對我來說,擁有可定製的列(a列的innerHTML)非常重要。但是我對ng-repeat的範圍有一些問題。有沒有辦法在aColumns的transclude中訪問ng-repeat範圍?ng-repeat和transclude的角度指令

<a-Table> 
    <a-Column><div class="abc">{{item.name}}</div></a-Column> 
    <a-Column>{{item.car}}</a-Column> 
</a-Table> 

一個表指令:

app.directive("aTable", function() { 
return { 
    restrict: "E", 
    transclude: true, 
    scope: {}, 
    template: "<table><tr ng-repeat='item in testValues'><td ng-transclude ></td></tr></table>", 
    link: function (scope, tAttrs, attrs, ctrl, transclude) { 
     scope.testValues = [{ 
      name: "Max", 
      car: "vw" 
     }, { 
      name: "Mike", 
      car: "bmw" 
     }] 
    }, 
}; 
}); 

一列指令:

app.directive("aColumn", function() { 
return { 
    restrict: "E", 
    required: '^aTable', 
    transclude: true, 
    scope: false, 
    link: function ($scope, $element, $attrs, ctrl, $transclude) { 
     if (!$transclude) { 
      console.log($transclude); 
     } 
     $transclude($scope, function (clone) { 
      console.log(clone); 
      $element.empty(); 
      $element.append(clone); 
     }); 
    } 
} 
}); 
+0

我相信你的指令模板裏只能有一個'ng-transclude'。因此,你不能在「ng-repeat」中使用它 - 這不在我頭頂,所以我不確定。也許使用'$ compile'會有所幫助。 – 2014-09-02 13:18:57

+1

@ m.e.conroy您好,非常感謝您的支持。可能有更多的一個ng-transclude。看到這裏http://stackoverflow.com/questions/16181602/angularjs-advanced-tabs-two-ng-transclude我認爲問題是孤立的範圍。 – Christoph 2014-09-02 13:24:46

+1

我很困惑。你的代碼有問題嗎?在[plunker](http://plnkr.co/edit/k2NqvLlIPKkMpIvh4sZV?p=preview)中似乎一切正常。 – bmleite 2014-09-02 13:26:16

回答

1

這裏http://plnkr.co/edit/61PzGPnqB79nhO5tDr7S?p=preview

刪除模板:

//template: "<table><tr ng-repeat='item in testValues'><td ng-transclude ></td></tr></table>", 

增加對循環,這是指對指數的特性:

scope.testValues = [{ 
     name: "Max", 
     car: "vw" 
    }, { 
     name: "Mike", 
     car: "bmw" 
    }] 

    angular.forEach(scope.testValues,function(v,k){ 
     var newscope = scope.$new(); 
     newscope.aTableIndex = k; 
     transclude(newscope,function(clone){ 
     element.append(clone); 
     }) 
    }) 

的HTML:

<div class="abc">{{ testValues[aTableIndex].name }}</div> 

....

<a-Column>{{ testValues[aTableIndex].car }}</a-Column> 

更新

刪除注入$ compi le(不需要),正如Christoph所建議的