AngularJS动态加载的元素,里面的ng-click无法触发?

在项目中,服务端返回了一个html字符串,写了一个filter,通过$sce.trustAsHtml(text)将字符串编译成可加载的html,但是元素里的ng-click事件无法触发,求解!!

   //字符串转html标签过滤器
    app.filter("htmlContent",["$sce",function($sce){
        return function(text){
            return $sce.trustAsHtml(text);
        }
    }]);

     //模拟数据
    var jsonArr = [{
        temp:"<h1 ng-click='showCoverBox()'>测试</h1>" 
    }];

    //点击事件
    $scope.showCoverBox = function(){
        console.log("测试");
    };
    
   //页面通过ng-repeat展示
    <li ng-repeat="item in jsonArr">
        div ng-bind-html="item.tmp|htmlContent"></div>
    </li>

有人说可以在directive中通过$compile服务,编译DOM,实现动态的事件绑定,但是我想要的是不用指令,有没有其他解决方案,求大神指教~

阅读 16.8k
2 个回答

这种情况必须用$compile, 你可以写一个directive, 已属性的形式加到div上

angular.module('app', []).directive('compileHtml', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(function () {return scope.$eval(attrs.ngBindHtml);},
          function(html) {
            ele.html(html);
            $compile(ele.contents())(scope);
          });
    }
  };
});

<div ng-bind-html="item.tmp|htmlContent" compile-html></div>
新手上路,请多包涵
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题