我想用angularjs创建一个表格模板。对我来说,拥有可自定义的列(a-column的innerHTML)非常重要。但是我对ng-repeat的isolatet范围有一些问题。有没有办法在aColumns的转换中访问ng-repeat范围?
<a-Table>
<a-Column><div class="abc">{{item.name}}</div></a-Column>
<a-Column>{{item.car}}</a-Column>
</a-Table>
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"
}]
},
};
});
a-column指令:
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 :(得分:1)
此处http://plnkr.co/edit/61PzGPnqB79nhO5tDr7S?p=preview:
删除模板:
//template: "<table><tr ng-repeat='item in testValues'><td ng-transclude ></td></tr></table>",
添加for循环,以及引用索引的属性:
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>
<强>更新强>
删除了注入$ compile(不需要),如Christoph
所建议的那样