简体   繁体   中英

Angularjs: attaching a click event in directive

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM