call function inside $sce.trustAsHtml() string in Angular js

前端 未结 1 1909
庸人自扰
庸人自扰 2020-11-27 06:56

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 co

相关标签:
1条回答
  • 2020-11-27 07:43

    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.

    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:

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

    0 讨论(0)
提交回复
热议问题