Shulte
Shulte

Reputation: 33

Angular: add ng-click inside directive

In my directive i using appendTo and ng-click inside it:

$("<div>" + "<a href='' ng-click='addIt()' + user + "</a></div>").appendTo '.user-class'

And ng-click doesn't work. Should i use $compile? How to use it in that case?

Upvotes: 1

Views: 939

Answers (2)

user1364910
user1364910

Reputation:

this code is a part of directive that make dropdown menu from json. There is no option to move this to directive template, so need to find solution how to make 'ng-click' works here.

Like Matthew, I am most curious as to which part(s) cannot be moved out into an external template / internal template function. It doesn't make much sense to me to have to re $compile a directive only to add a ng-click handler.

The senseful way would be to add the ng-click directive to a template. Either an external one, or a function returning a string value in the directive definition object.

Running $compile after the link step has finished is not a good idea performance wise, seeing as how it recompiles the entire DOM element your directive is attached to. Avoid doing so for as long as you possibly can.

.directive('myDir', function () {
  return {
    template: function (/*element, attrs*/) {
      return '<div><a href="" ng-click="addIt(user)">{{::user}}</a></div>';
    },
    link: function (scope, el, attrs) {
      scope.user = 'John';
    }
  };
});

This would result in the following DOM structure:

<div>
  <a href="" ng-click="addIt(user)">John</a>
</div>

jsbin

Upvotes: 2

BhagyashriK
BhagyashriK

Reputation: 525

Yes you will need $compile , inject $compile in directive and you can do it like this :

 var link = $compile("<div>" + "<a href='' ng-click='addIt()'" + user + "</a></div>")(scope);
 link.appendto('.user-class');

Upvotes: 1

Related Questions