user6824054
user6824054

Reputation:

Dynamically add AngularJS Directive to page to display and render the directive not working

If I type onto page

<liberty-directive></liberty-directive> 

That works fine.

However, I have database table with list of directive names.

So

<table>
    <tr ng-repeat="lib in vm.liberty">
        <td>{{lib.Tag}}</td>
    </tr>
</table>

So this is the object with the directive tag

{{lib.Tag}}  = <td class="ng-binding">&lt;liberty-directive&gt;&lt;/liberty-directive&gt;</td>

Viewing source it "looks fine" , but copy and paste to this it is changing, how to prevent that?

Upvotes: 2

Views: 66

Answers (1)

The.Bear
The.Bear

Reputation: 5855

To get it work, you have to compile your html in each iteration of ng-repeat (use $compile). For that, you can use a simple custom directive: (PLUNKER DEMO)

.directive('compileHtml', ['$compile', function($compile) {
  return function(scope, element, attrs) {
    element.html(attrs.compileHtml);
    $compile(element.contents())(scope);
  };
}]);

Then in your HTML use it like:

<tr ng-repeat="d in vm.data">
  <td compile-html="{{d.htmlContent}}"></td>
</tr>

Controller:

function myCtrl() {
    var vm = this;

    vm.data = [
        { "htmlContent": "<my-custom-directive></my-custom-directive>" }, 
        { "htmlContent": "<div>Custom: <span my-attr-directive></span></div>" },
        //... more items
    ];
}

Check this post if you want more examples.

Upvotes: 1

Related Questions