gpt4 book ai didi

javascript - 在 Angular js 的 $sce.trustAsHtml() 字符串中调用函数

转载 作者:可可西里 更新时间:2023-11-01 01:45:17 25 4
gpt4 key购买 nike

我正在使用 Angularjs 开发一个应用程序,并在我的页面中使用 $sce.trustAsHtml() 添加 HTML。我想在上面动态添加的内容中调用一个函数。我的 html 和脚本如下。

HTML

<div ng-app="ngBindHtmlExample">
<div ng-controller="ngBindHtmlCtrl">
<p ng-bind-html="myHTML"></p>
</div>
</div>

Javascript

angular.module('ngBindHtmlExample', ['ngSanitize'])

.controller('ngBindHtmlCtrl', ['$scope','$sce', function ngBindHtmlCtrl($scope, $sce) {
$scope.myHTML =$sce.trustAsHtml(
'I am an <code>HTML</code>string with <a href="#" ng-mouseover="removeExp()">links!</a> and other <em>stuff</em>');

$scope.removeExp = function (){
console.log('dfdfgdfgdfg');
}
}]);

jsfiddle

Click Here to see

最佳答案

这有点棘手,因为 ng-bind-html 只会插入普通的旧 html 而不会费心编译它(因此 html 中的任何指令都不会被 angular 处理。

诀窍是找到一种在模板更改时进行编译的方法。例如,您可以创建执行此操作的指令。它看起来像:

.directive('compileTemplate', function($compile, $parse){
return {
link: function(scope, element, attr){
var parsed = $parse(attr.ngBindHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }

//Recompile if the template changes
scope.$watch(getStringValue, function() {
$compile(element, null, -9999)(scope); //The -9999 makes it skip directives so that we do not recompile ourselves
});
}
}
});

然后你可以像这样使用它:

<p ng-bind-html="myHTML" compile-template></p>

请参阅此处的工作示例:

http://jsfiddle.net/3J25M/2/

关于javascript - 在 Angular js 的 $sce.trustAsHtml() 字符串中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297638/

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