2013-10-01 34 views
1

我在這裏找到了一個很棒的樹指令。 原因:http://jsfiddle.net/n8dPm/Angularjs:在指令中附加點擊事件

我想附加一個點擊處理程序。我將它添加到如下的p元素中,但它不起作用。什麼是錯誤的:

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

回答

2

您從編譯函數返回的功能是鏈接功能。擺脫鏈接屬性並將scope.testme向上移動到編譯函數返回的函數中。

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/

+0

+1 ..謝謝你這麼多:-)也,後隨QN。 http://stackoverflow.com/questions/19125551/angularjs-understanding-a-recursive-directive – bsr