2014-09-02 85 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所建议的