javascript 在 Angular js 中调用 $sce.trustAsHtml() 字符串中的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20297638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
call function inside $sce.trustAsHtml() string in Angular js
提问by Rajnikant Kakadiya
I am developing an app using Angularjs and adding HTML
using $sce.trustAsHtml()
in my page. I want to call a function in above dynamically added content. My html and script as below.
我正在使用 Angularjs 开发一个应用程序并在我的页面中添加HTML
using $sce.trustAsHtml()
。我想在上面动态添加的内容中调用一个函数。我的 html 和脚本如下。
HTML
HTML
<div ng-app="ngBindHtmlExample">
<div ng-controller="ngBindHtmlCtrl">
<p ng-bind-html="myHTML"></p>
</div>
</div>
Javascript
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
提琴手
回答by dtabuenc
It's a bit tricky because ng-bind-html
will simply insert plain old html and not bother compiling it (so any directives in the html will not be processed by angular.
这有点棘手,因为它ng-bind-html
只会插入普通的旧 html 而不会编译它(因此 html 中的任何指令都不会被 angular.js 处理)。
The trick is finding a way to compile whenever the template changes. For example, you could create a directive that does this. It would look something like:
诀窍是找到一种在模板更改时进行编译的方法。例如,您可以创建一个执行此操作的指令。它看起来像:
.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
});
}
}
});
You can then use it like this:
然后你可以像这样使用它:
<p ng-bind-html="myHTML" compile-template></p>
See the working example here:
请参阅此处的工作示例: