gpt4 book ai didi

angularjs - $sce.trustAsHtml 中的渲染指令

转载 作者:行者123 更新时间:2023-12-03 11:18:31 28 4
gpt4 key购买 nike

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

我正在尝试向 DOM 添加一个按钮,单击时应该执行绑定(bind)到它的函数。在这种情况下,它应该提醒“测试”。这是代码。

Controller

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>

最佳答案

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

这是因为 Angular 的工作原理是先编译然后链接。见conceptual overview一个很好的解释。

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

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

关于angularjs - $sce.trustAsHtml 中的渲染指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623118/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com