1

I found a great tree directive here. Original: http://jsfiddle.net/n8dPm/

I am trying to attach a click handler. I added it to the p element as below, but it is not working. What is wrong:

code http://jsfiddle.net/tHh5M/2/

module.directive("tree", function($compile) {
    return {
        restrict: "E",
        scope: {family: '='},
        template: 
            '<p ng-click="testme()">{{ family.name }}</p>'+
            '<ul>' + 
                '<li ng-repeat="child in family.children">' + 
                    '<tree family="child"></tree>' +
                '</li>' +
            '</ul>',
        compile: function(tElement, tAttr) {
            var contents = tElement.contents().remove();
            var compiledContents;
            return function(scope, iElement, iAttr) {
                if(!compiledContents) {
                    compiledContents = $compile(contents);
                }
                compiledContents(scope, function(clone, scope) {
                         iElement.append(clone); 
                });
            };
        },
        link: function (scope, elm, attrs) {
            scope.testme = function () {
                console.log('testme')
            };
        }
    };
});
bsr
  • 57,282
  • 86
  • 216
  • 316

1 Answers1

2

The function you return from the compile function is the link function. Get rid of the link property and move the scope.testme up into the function returned from the compile function.

    compile: function (tElement, tAttr) {
        var contents = tElement.contents().remove();
        var compiledContents;
        return function (scope, iElement, iAttr) {
            if (!compiledContents) {
                compiledContents = $compile(contents);
            }
            compiledContents(scope, function (clone, scope) {
                iElement.append(clone);
            });
            scope.testme = function () {
                console.log('testme')
            };
        };
    }

http://jsfiddle.net/tHh5M/3/

dnc253
  • 39,967
  • 41
  • 141
  • 157
  • +1.. thank you so very much :-) also, a followup qn. http://stackoverflow.com/questions/19125551/angularjs-understanding-a-recursive-directive – bsr Oct 01 '13 at 20:44