我有指令

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>",
      }
    });

Controller :
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并处理 Controller 中的click函数时。因为我是AngularJS的新手,所以一段时间以来一直在努力解决这个问题。请帮忙。

最佳答案

您不需要处理$sce即可满足您的目的。

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

HTML中,您需要directive

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

myVal中为 Controller 设置不同的值
$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

关于javascript - ng-click在编译后不起作用ng-bind-html,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21370080/

10-12 14:10
查看更多