directive not working inside that is ng-repeat bound

前端 未结 2 1799
小蘑菇
小蘑菇 2021-01-02 04:42

I have a table where the rows are repeated via ng-repeat. I am trying to create a template that generates columns for each row <

相关标签:
2条回答
  • 2021-01-02 05:11

    As Pavlo wrote, you can move the tr element to the template for the directive. Another option is to use a td element and directive that replaces your td with the template that you want to use.

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

    Directive 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

    0 讨论(0)
  • 2021-01-02 05:22

    As pointed out in comments the template of a directive should have single root element. So I would suggest you to move the tr element to the template of the directive, like this: http://plnkr.co/edit/YjLEDSGVipuKTqC2i4Ng?p=preview

    0 讨论(0)
提交回复
热议问题