指令在 <tr> ng 重复绑定的内部不起作用



我有一个表,其中的行通过ng-repeat重复。我正在尝试创建一个模板,为每行<tr> 生成列<td>

app.directive("customtd", function(){
  return {
    restrict: 'E',
    template: "<td>{{position.Name}}</td><td>{{position.Code}}</td>",
    replace: true,
    scope: {
      position: '='
    }
  }
});
<table>
  <tr ng-repeat="p in positions">
    <customtd position="p"></customtd>
  </tr>
</table>

问题是我的自定义td模板根本没有呈现。在这里,我打算将<customtd>替换为n个<td>s,这将根据我的数据对象上的属性数量来决定,但目前我只是试图获得一个简单的指令,该指令将输出两列。

MYPLUNKER:显示了这个问题的一个实例和指令代码。

正如注释中所指出的,指令的模板应该有一个根元素。因此,我建议您将tr元素移动到指令的模板中,如下所示:http://plnkr.co/edit/YjLEDSGVipuKTqC2i4Ng?p=preview

正如Pavlo所写,您可以将tr元素移动到指令的模板中。另一种选择是使用td元素和指令,用要使用的模板替换td

<table>
  <tr ng-repeat="p in positions">
    <td replace-me template="mytemplate.html" position="p"></td>
  </tr>
</table>

指令replaceMe

.directive("replaceMe", ["$compile", '$http', '$templateCache', function ($compile, $http, $templateCache) {
        return {
            restrict: 'A',
            scope: {
               position: "="
            },
            link: function (scope, element, attrs) {
                function getTemplate(template) {
                    $http.get(template, {cache: $templateCache}).success(function (templateContent) {
                        element.replaceWith($compile(templateContent)(scope));
                    });
                }
                scope.$watch(attrs.template, function () {
                    if (attrs.template) {
                        getTemplate(attrs.template);
                    }
                });

            }
        }
    }]);

mytemplate.html

<td>{{position.Name}}</td>
<td>{{position.Code}}</td>
<td another-my-directive></td>

plunker

最新更新