在$ sce.trustAsHtml中渲染指令

rjm*_*226 23 angularjs angularjs-directive angularjs-scope

我在这里包含了一个Plunker:http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p = preview

我正在尝试向DOM添加一个按钮,当单击时应该执行绑定到它的函数.在这种情况下,它应警告"测试".这是代码.

调节器

app.controller('MainCtrl', function($scope, $sce) {
        $scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');  

        $scope.testAlert = function () {
            alert('testing')
        };
});
Run Code Online (Sandbox Code Playgroud)

HTML

<body ng-controller="MainCtrl">
    <div ng-bind-html="trustedHtml"></div>
</body>
Run Code Online (Sandbox Code Playgroud)

Dav*_*yon 26

$sce.trustAsHtmlng-bind-html不是为了建立与指令HTML.这种技术不起作用.

这是因为角度通过首先编译然后链接起作用.请参阅概念性概述以获得良好的解释.

简而言之,当你链接你定义的HTML时trustAsHtml,对于编译(因此理解)ng-click指令而言,角度为时已晚.

为了动态添加HTML,您应该查看$compile服务(和/或指令). 文件在这里.

  • 对,这是一个新的plunker,展示了如何通过$ compile实现这一目标.http://plnkr.co/edit/3CewDscih8diAo4mMSwJ?p=preview以下是帮助我解决此问题的其他一些资源:http://stackoverflow.com/questions/18157305/angularjs-compiling-dynamic-html-strings-from-数据库 (17认同)
  • 我希望您具体说明如何解决问题. (2认同)

小智 10

对不起,我的英语不好.

对于Angular 1.6.1,我找到了一个适合我的解决方案.

模板:

<div ng-bind-html="trustAsHtml(content);" init-bind> </div>
Run Code Online (Sandbox Code Playgroud)

在控制器中:

    $scope.trustAsHtml = function(string) {
        return $sce.trustAsHtml(string);
    };
Run Code Online (Sandbox Code Playgroud)

指示:

.directive('initBind', function($compile) {
return {
        restrict: 'A',
        link : function (scope, element, attr) {
            attr.$observe('ngBindHtml',function(){
                if(attr.ngBindHtml){
                     $compile(element[0].children)(scope);
                }
            })
        }
    };
})
Run Code Online (Sandbox Code Playgroud)