【问题标题】:Rendering directives within $sce.trustAsHtml$sce.trustAsHtml 中的渲染指令
【发布时间】:2014-01-04 13:31:50
【问题描述】:

我在这里添加了一个 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>

【问题讨论】:

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

$sce.trustAsHtmlng-bind-html 并不是要使用指令构建 HTML。这种技术行不通。

这是因为 Angular 的工作原理是先编译然后链接。请参阅conceptual overview 以获得很好的解释。

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

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

【讨论】:

【解决方案2】:

对于 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);
                }
            })
        }
    };
})

【讨论】:

  • 如果有人愿意尝试,这也是一个解决方案。
  • 太棒了!大量使用指令和 $compile。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
  • 2021-12-18
  • 2015-05-11
  • 2013-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多