AngularJS – Append element to each ng-repeat iteration inside a directive

I’m using a ng-repeat inside a <tr> element together with a directive.

Html:

<tbody>
  <tr ng-repeat="row in rows" create-table>
    <td nowrap ng-repeat="value in row | reduceString>{{value}}</td>
  </tr>
</tbody>

Directive:

app.directive('createTable', function () {
        return {

            link: function (scope, element, attrs) {
                var contentTr = scope.$eval('"<tr ng-show=&quot;false&quot;><td>test</td></tr>"');
                $(contentTr).insertBefore(element);
            }
        }
    }
);

Although I can append a new <tr> element to each iteration, I’m not able to get angular code executed after it’s been added to the DOM (for example the ng-show inside the <tr>). Am I missing something obvious?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The reason why you don’t get Angular binding inside your child is because you lack compiling it. When the link function runs, the element has already been compiled, and thus, Angular augmented. All you got to do is to $compile your content by hand. First of, don’t eval your template, or you will lose your binding tips.

app.directive('createTable', function ($compile) {
  return {
    link: function (scope, element, attrs) {
      var contentTr = angular.element('<tr ng-show=&quot;false&quot;><td>test</td></tr>');
      contentTr.insertBefore(element);
      $compile(contentTr)(scope);
    }
  }
});

Another tip: you never enclose your elements in jQuery ($). If you have jQuery in your page, all Angular elements are already a jQuery augmented element.

Finally, the correct way to solve what you need is to use the directive compile function (read ‘Compilation process, and directive matching’ and ‘Compile function’) to modify elements before its compilation.

As a last effort, read the entire Directive guide, this is a valuable resource.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply