2014-10-17 40 views
2

我一直在寻找几个小时,我似乎无法找到使用ng-repeat进行检索时如何解析HTML代码。我检出了$ sce.trustAsHtml,但我不知道如何将其应用于我的代码中。在ng-repeat中解析html

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/

谢谢。

回答

5

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

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

,只是使用ng-bind-html

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

,你是好去: -

Plnkr

随着你在做什么,在绑定的HTML将在由插值指令处理时,在元素中显示为textcontent。

+1

忘了这个!好东西。 – dannypaz 2014-10-17 21:37:01

+0

@PSL就是这样!我之前尝试ngSanitize,但没有奏效。现在我知道为什么。我认为angular.min.js是完整的。事实证明它没有angular-sanitize.js。现在,我也包括这一点,它的作品。谢谢 – w1n78 2014-10-17 21:44:25

+0

@ w1n78 yup !!,不客气.. :) – PSL 2014-10-17 22:27:19

1

我的第一个倾向(因为从你的例子中,你只是返回链接)是建议你从返回的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> 

但是,如果你MUST有HTML中的字串JSON文件,我想看看$compile。有一些关于底部的例子可以帮助你如何创建一个指令来编译你的'url'字符串为HTML

+0

我用链接作为一个简单的例子来了解如何做到这一点。我将要处理的数据有更多的html标签,如文本样式。我会看看$ compile。感谢您的建议。 – w1n78 2014-10-17 21:46:53