ps0604 ps0604 - 5 months ago 28
AngularJS Question

Adding ng-click to div created with angular.element

I have the following directive that has two children

div
s. The second div (created with
angular.element
) should be clickeable. Since I created it with
angular.element
, I'm trying to add
ng-click
with the
attr
function, but this doesn't work. What's wrong with this code?

app.directive('mydir', function () {

var directive = {};

directive.restrict = 'EA';

directive.replace = true;

directive.scope = {
control: '=',
};

directive.template = '<div id="root"></div>';

directive.link = function (scope, element, attrs) {

var wrap = angular.element('<div id="wrap"></div>');
element.append(wrap);
var node = angular.element('<div id="node"></div>');
node.attr('ng-click', 'toggle()'); // <--- this doesn't work
wrap.append(node);

scope.toggle = function () {
alert('clicked');
};
});

return directive;

});

Answer

The element has to be compiled using angular's $compile service:

       app.directive('mydir', function ($compile) { // added dependency here

                var directive = {};

                directive.restrict = 'EA';

                directive.replace = true;

                directive.scope = {
                     control: '=',
                };

                directive.template = '<div id="root"></div>';

                directive.link = function (scope, element, attrs) {

                        var wrap = angular.element('<div id="wrap"></div>');
                        element.append(wrap);                               
                        var node = angular.element('<div id="node"></div>');
                        node.attr('ng-click', 'toggle()');   // <--- this doesn't work
                        var content = $compile(node)(scope);
                        wrap.append(content);

                        scope.toggle = function () {
                            alert('clicked');
                        };
                });

                return directive;

            });

Here's a short tutorial on using $compile. Hope that helps