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')
            };
        }
    };
});

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

+1.. thank you so very much :-) also, a followup qn. stackoverflow.com/questions/19125551/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.