【问题标题】:Click event not firing when attached in directive compile在指令编译中附加时单击事件未触发
【发布时间】:2014-11-01 15:14:52
【问题描述】:

我正在尝试从 compile 函数内部为 li 附加点击事件,我可以看到 dom 中存在 ng-click,但未触发该事件。

compile:function (elem, attrs){

      //elem.find('li').attr('data-ng-click', 'hello()');
      elem.find('li').attr('ng-click', "hello($event)");

      return function(scope, elem, attrs) {
          scope.hello = function ($event) {
            console.log($event);
            alert('click triggered')
          };       
 }

Plnkr : http://plnkr.co/edit/o8JyJM?p=preview

【问题讨论】:

  • 您能否更笼统地解释一下您要完成的工作?

标签: angularjs


【解决方案1】:

仅仅添加一个本身就是指令的属性不会导致它被处理。每个将包含指令的元素都需要通过$compile 运行以创建链接函数,然后需要使用传递给它的范围对象调用链接函数(通常使用$rootScope.new() 创建)。综上所述,通常有更简单的方法来完成您想要的,只需使用模板中的ng-click(已编译)或使用element.bind("click",function(evt){})。我也会在这里修复 plunkr。

【讨论】:

    【解决方案2】:

    范围在指令的编译阶段不可用。它仅在链接阶段可用。我建议您将编译切换为链接功能(如果您对上面的 sn-p 中的编译功能没有特定需求。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2011-10-07
      相关资源
      最近更新 更多