0

我正在创建一个允许用户创建预览 html 内容的 UI。

出于这个问题的目的,假设我有以下对象数组:

modules = [
    {
        id: 0,
        type: 'title',
        content: 'This is the title',
        subtitle: 'This is the subtitle'
    },
    {   
        id: 1,
        type: 'intro', 
        content: 'This is the <b>intro copy</b>. This is the intro copy!'
    },
    {   
        id: 2,
        type: 'title',
        content: 'This is the title'
    }
];

我创建了一个指令,该指令循环遍历对象以根据类型选择模板并使用 $compile 来呈现不同的模块。

app.directive('module', function( $compile ){

    // Define templates as strings
    var titleTemplate = '<h1>' + 
                            '{{ module.content }}' + 
                        '</h1>' +
                        '<h3 ng-show="module.subtitle">{{ module.subtitle }}</h3>';

    var introTemplate = '<p>' +
                            '{{ module.content }}' +
                        '</p>' + 
                        '<p ng-show="module.secondContent"><em>{{ module.secondContent }}</em></p>';

    // Select the current template by value passed in through scope.module.type

    var getTemplate = function(moduleType) {

        var template = '';

        switch(moduleType) {
            case 'title':
                template = titleTemplate;
                break;
            case 'intro':
                template = introTemplate;
                break;
            case 'ribbon': 
                template = ribbonTemplate; 
        }

        return template;

    };

    // Pass the scope through to the template for access in the module

    var linker = function( scope, element, attrs ) {
        element.html( getTemplate( scope.module.type ) ).show();
        $compile( element.contents() )( scope );
        console.log(attrs);
    };

    return {
        restrict: 'E',
        link: linker,
        replace: true,
        scope: {
            module : '='
        }
    }
});

最后,在我的 html 中

<module module="module" ng-repeat="module in modules"></module>

我遇到的问题是,当我在内容中有一个 html 元素时,例如<b>intro copy</b>in modules[1].content,该元素被呈现为一个字符串,而不是像预期的那样加粗文本。

4

1 回答 1

0

要从角度的 var 解释 HTML,您需要使用该ng-bind-html指令。它将解释 HTML 而不仅仅是将其显示为字符串。

例子:

$scope.myhtmlvar = "<b>I'm bold</b";

<div ng-bind-html="myhtmlvar"></div>

这看起来不错,但实际上不起作用。为什么 ?有一个很好的理由:解释 HTML 是不安全的。想象一下解释整个 html,用户可以添加任意数量的 javascript,并且可以完全注入自己的行为并破解您的应用程序。为避免此问题,您需要将 ngSanitize 角度库添加到您的项目中。

https://ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-sanitize.js

并将其注册到您的应用程序中

var app = angular.module('testApp', ['ngSanitize']);

从现在开始,您的 ng-bind-html 将自动清理您提供给他的 html。前面的两条线现在应该可以工作了。

这是一个工作的plunker作为例子

希望它有所帮助。

于 2015-06-24T15:43:37.327 回答