javascript innerHTML返回文本而不是html

时间:2015-12-01 19:07:02

标签: javascript angularjs text innerhtml

我在angularjS中做了一个应用程序,我有这个功能来删除#(哈希)并将它们组合成链接。

$scope.getAllHashes = function(event){

    var x = event;
    var collect = '';
    var link = '';

    for (i = 0; x.length > i; i++) { 

        //remove #
        link = x[i].substr(1);

        collect += "<a href='#/search/" + link + "'>" + x[i] + "</a> ";

    }
    return document.getElementsByClassName('hashes').innerHTML = collect;
};

返回文字:

<a href='#/search/aaa'>#aaa</a> <a href='#/search/bbb'>#bbb</a> <a href='#/search/cccc'>#cccc</a>

而不是链接:

#aaa #bbb #ccc

源来自这个数组:

$scope.events = 
[
    {

            id: 1,
            datetime: 'FRI, 6 NOV 10:00 AM',
            title: 'Event Title goes here - lalelalela',
            address: {
                road: '650 Address Rd',
                city: 'Toronto',
                state: 'Ontario',
                postal: 'A1B1C3',
                country: 'CA'
            },
            hashes: ['#aaa','#bbb','#cccc']

    }, .....

这是来自html源代码的代码

<span class="hashes ng-binding">
            &lt;a href='#/search/aaa'&gt;#aaa&lt;/a&gt; &lt;a href='#/search/bbb'&gt;#bbb&lt;/a&gt; &lt;a href='#/search/cccc'&gt;#cccc&lt;/a&gt; 
</span>

我不确定为什么它显示为文本而不是html。

1 个答案:

答案 0 :(得分:1)

对于HTML,您需要使用ng-bind-html

<p ng-bind-html="getHashes({ data: eventObject.hashes })"></p>

确保您并且包含对ngSanitize的依赖。请参阅文档https://docs.angularjs.org/api/ng/directive/ngBindHtml