如何使用angularjs ng-repeat将html字符串从数组转换为html

How to turn an html string from an array into html using angularjs ng-repeat?

本文关键字:html 数组 转换 字符串 angularjs ng-repeat 何使用      更新时间:2023-09-26

我有以下数组,其中每个项目的值都是一个 html 字符串。如何将此字符串转换为可执行的 html,以便可以显示它?

[
{html:'<button>name</button>'},
{html:'<table > <thead> <tr> <th>#</th> <th>UserName</th> <th>Time</th> <th>Comments</th> <th>Reply</th> <!-- <th>like or dislike</th> --> </tr> </thead> <tbody> <tr> <td>1,001</td> <td><a href="#" >Lorem</a></td> <td>2014-10-31</td> <td>ipsum</td> <td> <button type="submit" > <span ></span></button></td> </tr> <tr> <td>1,002</td> <td>amet</td> <td><a><span ></span></a></td> <td><a><span ></span></a></td> <td> <button type="submit" > <span ></span></button></td> </tr> <tr> <td>1,003</td> <td>Integer</td> <td>nec</td> <td>odio</td> <td> <button type="submit"> <span></span></button></td> </tr> <tr> <td>1,003</td> <td>libero</td> <td>Sed</td> <td>cursus</td> <td> <button type="submit" > <span></span></button></td> </tr> </tbody> </table>'},
{html:'<p>myhtml</p>'}
]

请参阅此处的代码笔:http://codepen.io/chriscruz/pen/YPwVmb

请参阅下面的 HTML

    <table class="table table-striped table-bordered table-hover" id="dataTables-example">
        <thead>
            <th>Email</th>
        </thead>
        <tbody>
            <tr ng-repeat="(id,item) in data">
                <td>{{item.html}}</td>
            </tr>
        </tbody>
    </table>

</body>

Javascript 和 Angular JS

    var app = angular.module("app", ["firebase"]);
    app.factory("TestArray", ["$firebase", function($firebase) {
        lst = [
        {html:'<button>name</button>'},
        {html:'<table > <thead> <tr> <th>#</th> <th>UserName</th> <th>Time</th> <th>Comments</th> <th>Reply</th> <!-- <th>like or dislike</th> --> </tr> </thead> <tbody> <tr> <td>1,001</td> <td><a href="#" >Lorem</a></td> <td>2014-10-31</td> <td>ipsum</td> <td> <button type="submit" > <span ></span></button></td> </tr> <tr> <td>1,002</td> <td>amet</td> <td><a><span ></span></a></td> <td><a><span ></span></a></td> <td> <button type="submit" > <span ></span></button></td> </tr> <tr> <td>1,003</td> <td>Integer</td> <td>nec</td> <td>odio</td> <td> <button type="submit"> <span></span></button></td> </tr> <tr> <td>1,003</td> <td>libero</td> <td>Sed</td> <td>cursus</td> <td> <button type="submit" > <span></span></button></td> </tr> </tbody> </table>'},
        {html:'<p>myhtml</p>'}
        ]
        return lst;
    }]);
    app.controller("ctrl", ["$scope","TestArray", function($scope,TestArray) {
        $scope.data = TestArray;
        //$scope.data = Emails;
    }]);

这是我希望看到的预期结果:http://codepen.io/chriscruz/pen/pvgwzw?editors=101

这是更新的代码笔

您需要添加angular-sanitize.js文件

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular-sanitize.js"></script>

并在app中导入ngSanitize模块

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

然后你可以使用 ng-bind-html 指令绑定 HTML

<td ng-bind-html="item.html"></td>