【问题标题】:Angular directive with ng-repeat and transclude带有 ng-repeat 和 transclude 的 Angular 指令
【发布时间】:2014-10-26 18:13:46
【问题描述】:

我想用 angularjs 创建一个表格模板。对我来说,拥有可定制的列(a 列的 innerHTML)很重要。但是我对 ng-repeat 的孤立范围有一些问题。有什么方法可以访问 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);
         });
     }
 }
 });

【问题讨论】:

  • 我相信你的指令模板中只能有一个ng-transclude。因此你不能把它放在ng-repeat 里面——这不是我的想法,所以我不确定。也许使用$compile 会有所帮助。
  • @m.e.conroy 您好,感谢您的遮阳篷。可能有多个 ng-transclude。看到这里stackoverflow.com/questions/16181602/…我认为问题是孤立的范围。
  • 我很困惑。你的代码有问题吗?在这个plunker 中一切似乎都运行良好。
  • @bmleite 感谢您的评论。它确实适用于您的 plunker。不幸的是,它似乎不适用于 angular 的最新稳定版本(1.2.23)。在您的 plunker(角度版本 1.3.0-beta.5)中一切正常。
  • 它适用于 1.3.0-beta.1 至 1.3.0-beta.10 版本。对于 1.3.0-beta.11 到 1.3.0-beta.19,它不起作用。

标签: angularjs


【解决方案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>

更新

按照 Christoph 的建议,移除了注入 $compile(不需要)

【讨论】:

    猜你喜欢
    • 2015-05-04
    • 2023-03-05
    • 1970-01-01
    • 2016-07-07
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多