【问题标题】:call function inside $sce.trustAsHtml() string in Angular js在 Angular js 中调用 $sce.trustAsHtml() 字符串中的函数
【发布时间】:2013-11-30 07:11:28
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

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

    【讨论】:

    • 这正是我所需要的!谢谢!
    • 太棒了,正是我需要的
    • 经过调整后这对我有用。我在离子应用程序中使用它,它不喜欢函数 getStringValue(),只在模拟器中提醒你。我需要 var getStringValue = function()。
    • 很棒的家伙。这对我有帮助
    猜你喜欢
    • 2019-06-02
    • 2014-07-14
    • 2014-04-11
    • 2021-01-26
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多