2

Can I dynamically load an AngularJS Directive templateUrl when working in a table?

I have the following HTML, repeating a tr with a fw-rule directive:

<tbody>
  <tr ng-repeat="rule in data | orderBy:predicate:reverse" fw-rule="rule">
  </tr>
</tbody>

I would like the contents of that tr to different, depending on the state of an "edit" variable.

One of my partials is below (the other is just a variation on layout):

<td><input type="checkbox"></td>
<td ng-click="isEditing=!isEditing">{{ fwRule.name }}<br><span class="rule-description">{{ fwRule.description }}</span></td>
<td>{{ fwRule.source }}</td>
<td>{{ fwRule.destination }}</td>
<td>{{ fwRule.protocol }}</td>
<td>{{ fwRule.schedule }}</td>
<td>{{ fwRule.action }}</td>
<td>{{ fwRule.reporting }}</td>

I reviewed the following two questions here at SO, which almost gave me the answer:

However, they both call to write the directive's template using a <div ng-include"getTemplateUrl()"></div>, such are the following:

app.directive('fwRule', function () {
  return {
    restrict: 'A',
    scope: {
      fwRule: '='
    },
    controller: function ($scope) {
      $scope.getTemplateUrl = function () {
        // a check would be made here to return the appropriate partial
        return 'partials/RuleEditTableRow.html'
      }
    },
    link: function (scope, element, attrs) {
    },
    template: '<div ng-include="getTemplateUrl()"></div>'
  };
});

This does not work in my case through, since div is not a valid child of tr (nor is span, which I also tried). As a result the browser renders that content outside the table.

Is there a way I can dynamically update the template of a directive, without using ng-include, so that it can behave inside a table?

Community
  • 1
  • 1
Nicholas Pappas
  • 10,439
  • 12
  • 54
  • 87

1 Answers1

0

You can use the $compile service to compile the correct template

app.directive('fwRule', function ($compile) {
    return {
        restrict: 'A',
        scope: {
            fwRule: '='
        },
        controller: function ($scope) {},
        link: function ($scope, element, attrs) {
            var template = '<td>cell 1</td><td>cell 2</td>';

            angular.element(element).html(template);
            $compile(element.contents())($scope);
        }
    };
});

I think I have it working with your code in this fiddle: http://jsfiddle.net/ztv5gwwx/4/

TwitchBronBron
  • 2,783
  • 3
  • 21
  • 45