AngularJS 指令里用$compile,ngclick依然不起作用?

新手上路,请多包涵

由于用了ngTable,且需求要求表格的标题可以拉开(所以用了resize),所以导致每次拉resize的小角标的时候,就会误触发ngTable的排序。我希望移除th上的"ng-click='sortBy($colum,$event)'",将这个ngClick动态地放到th里面包含的span上。
我在指令里用了$compile,运行后可以看到html上有ng-click,但是看Event Listeners是没有的,自然点击也没有反应。求求大神们帮助!!!

以下是简要代码
执行指令前的html代码:

<th title  ng-click="sortBy($colum,$event)" >
  <div> 
   <span>title1 </span>
  </div>
</th>

执行指令后的html代码:

<th title>
  <div> 
   <span ng-click="sortBy($colum,$event)" >title1 </span>
  </div>
</th>

指令JS代码:

.directive('tableTitle',function($parse,$compile){
 return{
    restrict:'A',
    link:function(scope,elem,attrs,controller){
      scope.$watch('params',function(newParams,oldParams){
       if(!(newParams === oldParams || !newParams)){
         var trTitle = xxxx; //ngTable生成的第一行
         var thArray = trTitle.children; //全部标题的集合
        
         //以thArray[1]为例子
         var ngclick = thArray[1].attributes.getNamedItem('ng-click').cloneNode(true);
         
         var span = thArray[1].children[0].children[0];
         var spanWithNgClick = angular.copy(span);
         angular.element(spanWithNgClick)[0].attributes.setNamedItem(ngclick); //加入ngclick属性节点
         thArray[1].children[0].renmoveChild(span); //把旧的不带ngclick的span移除
         var $html = angular.element(thArray[1].children[0]).html(
                 $compile(spanWithNgClick.outerHtml)(scope));
         angular.element(thArray[1].children[0]).append($html); //添加新的戴ngclick的span
         
         angular.element(thArray[1]).removeAttr('ng-click');
         var th = angular.copy(thArray[1]);
         trTitle.removeChild(thArray[1]); //把旧的带有ngclick的th移除
         trTitle.appendChild(th);//添加不带ngclick新的th
       }
       })
    
    },

    }
});

执行后的html代码照片(这是公司的项目,在内网里,没法截图,只好拍照了):
图片描述

阅读 1.5k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进