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

时间:2013-11-30 07:11:28

标签: javascript angularjs

我正在使用Angularjs开发一个应用,并在我的页面中使用HTML添加$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

Click Here to see

1 个答案:

答案 0 :(得分:46)

这有点棘手,因为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/