小编gir*_*nse的帖子

从数据库编译动态HTML字符串

情况

嵌套在我们的Angular应用程序中的是一个名为Page的指令,由一个控制器支持,该控制器包含一个带有ng-bind-html-unsafe属性的div.这被分配给名为'pageContent'的$ scope var.此var从数据库中分配动态生成的HTML.当用户翻转到下一页时,会调用DB,并将pageContent var设置为这个新的HTML,它将通过ng-bind-html-unsafe在屏幕上呈现.这是代码:

页面指​​令

angular.module('myApp.directives')
    .directive('myPage', function ($compile) {

        return {
            templateUrl: 'page.html',
            restrict: 'E',
            compile: function compile(element, attrs, transclude) {
                // does nothing currently
                return {
                    pre: function preLink(scope, element, attrs, controller) {
                        // does nothing currently
                    },
                    post: function postLink(scope, element, attrs, controller) {
                        // does nothing currently
                    }
                }
            }
        };
    });
Run Code Online (Sandbox Code Playgroud)

Page指令的模板(上面的templateUrl属性中的"page.html")

<div ng-controller="PageCtrl" >
   ...
   <!-- dynamic page content written into the div below -->
   <div ng-bind-html-unsafe="pageContent" >
   ...
</div>
Run Code Online (Sandbox Code Playgroud)

页面控制器

angular.module('myApp') …
Run Code Online (Sandbox Code Playgroud)

html dom compilation dynamic angularjs

131
推荐指数
3
解决办法
16万
查看次数

标签 统计

angularjs ×1

compilation ×1

dom ×1

dynamic ×1

html ×1