FlavienBert
FlavienBert

Reputation: 1684

Angular : How to compile a directive from a link function?

I created a directive with this link function:

link : function (scope, element, attrs, controller) {
         var markdownContent = {};    
         markdownContent.result = element.text();
         markdownContent.result += '<button ng-click="console.log("test")" class="btn btn-primary btn-xs" ><i class="icon-edit"></i></button>'; 
                    }
        element.html(markdownContent.result);

The trouble is that the ng-click directive isn't working.

I am pretty sure that the problem is that I need to compile for say to angular that I need to check this element. But I don't understand the syntax and the process...

If someone can help me it will be great!

EDIT : HERE MY PLUNKER plunker

It doesn't work because when I click on the button the function test() isn't called

Upvotes: 0

Views: 1959

Answers (1)

Sarah
Sarah

Reputation: 1331

You can use the $compile service, as demonstrated in this Plunk.

The relevant content:

app.directive("myDir", function($compile){
  return function (scope, element, attrs) {
    var markdownContent = {};    
    markdownContent.result = element.text();
    markdownContent.result += '<button ng-click="test()" class="btn btn-primary btn-xs" >Hello</button>'; 
    element.replaceWith($compile(markdownContent.result)(scope));
  };
});

And the corresponding HTML: <div my-dir></div>

This assumes the test function is in scope, like so:

app.controller("ctrl", function($scope) {
  $scope.test = function() { console.log("Test!"); };
});

Edit

As Dave mentioned in the comments, the content passed to $compile should have a single root element. You could wrap it in a <div>, as Dave suggested. Here is a working version of your Plunk with that edit.

Upvotes: 2

Related Questions