小编典典

ng-click在编译后不起作用ng-bind-html

angularjs

我有指令

app.directive("dir", function($compile, $sce){
      return{
        restrict: "E",
        link: function(scope, element, attr){
          scope.$watch('content',function(){
            var html = $sce.trustAsHtml(attr.content);
            scope.alabala = $compile(html)(scope);
          },true);
        },
        template: "<div ng-bind-html='alabala'></div>",
      }
    });

控制器:

function MainController($scope, $http, customService, $location, $sce, $compile){
    $scope.init = function(){
        customService.get().success(function(data) {
                 var html = $sce.trustAsHtml(data);
                $("#dir").attr("content", data);

            });
    };
}

在索引页面上,我有:

<div id="div" ng-controller="MainController" class="pull-right span3" ng-init="init()">
      <dir id="dir" ></dir>
</div>

每当包含不同的html时,我的自定义服务都会返回

<button ng-click='click()'>Click me</button>

我想做的是每次在指令的内容中推送不同的值以对其进行编译并将其放入html并处理控制器中的click函数时。因为我是AngularJS的新手,所以一段时间以来一直在努力解决这个问题。请帮忙。


阅读 361

收藏
2020-07-04

共1个答案

小编典典

您不需要处理$ sce即可达到目的。

您可以将HTMLas字符串传递给指令。在指令中编译后,它将起作用。

HTML您需要的地方directive

<dir id="dir" content="myVal"></dir>

myVal控制器中设置其他值

$scope.myVal = '<button ng-click=\'buttonClick()\'>I\'m button</button>'; // HTML as string

directive

myApp.directive('dir', function($compile, $parse) {
    return {
      restrict: 'E',
      link: function(scope, element, attr) {
        scope.$watch(attr.content, function() {
          element.html($parse(attr.content)(scope));
          $compile(element.contents())(scope);
        }, true);
      }
    }
  })

检查 [**Demo**](http://plnkr.co/edit/v02xk1o3ORKaptzo40pj?p=preview)

2020-07-04