在$ sce.trustAsHtml中渲染指令

时间:2013-12-16 23:32:21

标签: 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')
        };
});

HTML

<body ng-controller="MainCtrl">
    <div ng-bind-html="trustedHtml"></div>
</body>

2 个答案:

答案 0 :(得分:26)

$sce.trustAsHtmlng-bind-html并不意味着使用指令构建HTML。这种技术不起作用。

这是因为角度通过首先编译然后链接起作用。请参阅conceptual overview以获得良好的解释。

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

为了动态添加HTML,您应该查看$compile服务(和/或指令)。 Docs are here

答案 1 :(得分:10)

抱歉我的英语不好。

对于Angular 1.6.1,我找到了一个对我有用的解决方案。

模板:

<div ng-bind-html="trustAsHtml(content);" init-bind> </div>

在控制器中:

    $scope.trustAsHtml = function(string) {
        return $sce.trustAsHtml(string);
    };

指令:

.directive('initBind', function($compile) {
return {
        restrict: 'A',
        link : function (scope, element, attr) {
            attr.$observe('ngBindHtml',function(){
                if(attr.ngBindHtml){
                     $compile(element[0].children)(scope);
                }
            })
        }
    };
})
相关问题