我正在使用 Angularjs 开发一个应用程序并添加HTML
using $sce.trustAsHtml()
在我的页面中。我想在上面动态添加的内容中调用一个函数。我的 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
点击这里查看
这有点棘手,因为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/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)