【问题标题】:parse html within ng-repeat在 ng-repeat 中解析 html
【发布时间】:2014-12-13 12:56:20
【问题描述】:

我已经搜索了几个小时,但在使用 ng-repeat 检索时似乎找不到如何解析 HTML 代码。我检查了 $sce.trustAsHtml 但我不知道如何在我的代码中应用它。

html 文件:

<div ng-app="myApp">
<div ng-controller="MyCtrl">
    <h2>My Links</h2>
    <table class="table table-bordered">
        <thead>
            <tr>
                <td>Name</td>
                <td>URL</td>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="stuff in myStuff()">
                <td>{{stuff.name}}</td>
                <td>{{stuff.url}}</td>
            </tr>
        </tbody>
    </table>
</div>

javascript

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {
$scope.myStuff = function() {
    return [
        {
            'name':'Google',
            'url':'<a href="http://google.com">Google</a>'
        },
        {
            'name':'Yahoo',
            'url':'<a href="http://yahoo.com">Yahoo</a>'
        },
        {
            'name':'Microsoft',
            'url':'<a href="http://microsoft.com">Microsoft</a>'
        }
    ];
};
});

它正在显示 HTML 源代码,但我希望它编译代码。我的 JS 方法错了吗?一旦弄清楚这一点,我将使用 $http 指令将其应用于 json 文件。任何人都可以解释一下吗?我的代码在http://jsfiddle.net/s2ykvy8n/

谢谢。

【问题讨论】:

    标签: html json angularjs ng-repeat


    【解决方案1】:

    包含ng-sanitize 脚本并在您的模块中添加依赖项。

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

    只需使用ng-bind-html

         <td ng-bind-html="stuff.url"></td>
    

    你很高兴:-

    Plnkr

    通过你所做的,绑定中的 html 在被插值指令处理时将显示为元素中的文本内容。

    【讨论】:

    • 忘了这个!好东西。
    • @PSL 就是这样!我之前尝试过 ngSanitize 但没有用。现在我知道为什么了。我假设 angular.min.js 是完整的。原来它没有 angular-sanitize.js。现在我也包括了它,它可以工作。谢谢
    【解决方案2】:

    我的第一个倾向(因为从您的示例中,您只是返回链接)是建议您从返回的 json 中删除 html,并将 url 作为字符串返回。

    格式:

    {
        'name': 'Google',
        'url': 'http://google.com'
    }
    

    那么你的 HTML 看起来像这样,

    <tbody>
        <tr ng-repeat="stuff in myStuff()">
            <td>{{stuff.name}}</td>
            <td><a href="{{stuff.url}}">{{stuff.name}}</a></td>
        </tr>
    </tbody>
    

    但是,如果您必须在您的 json 文件中包含 HTML 字符串,我会查看 $compile。底部有一些示例可以帮助您了解如何创建指令以将“url”字符串编译为 HTML

    【讨论】:

    • 我用链接作为一个简单的例子来了解如何做。我将要处理的数据有更多的 html 标签,比如文本样式。我会看看$compile。谢谢你的建议。
    猜你喜欢
    • 2015-02-11
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 2016-05-29
    • 2016-04-02
    • 2016-04-06
    • 1970-01-01
    相关资源
    最近更新 更多