2013-04-02 185 views
61

HTML这是我的模板如何渲染角模板

<div class="span12"> 
     <ng:view></ng:view> 
</div> 

,这是我的看法模板

<h1>{{ stuff.title}}</h1> 

{{stuff.content }} 

现在我得到content为html,我想显示,鉴于。

但我所得到的只是原始的html代码。我怎么能渲染为实际的HTML

+2

哪里HTML是从哪里来的?在不同情况下,您需要'ngBindHtmlUnsafe','ngSanitize'或自定义指令。 –

+0

html来自我的数据库 – user194932147

+1

内容*绝对*可信吗? –

回答

93

使用 -

<span ng-bind-html="myContent"></span> 

你需要告诉角度不要逃避它。

+0

这是一个错字 - 他的意思是''。 –

+10

在AngularJS 1.2中API已经改变。 http://stackoverflow.com/questions/18340872/how-do-you-use-sce-trustashtmlstring-to-replicate-ng-bind-html-unsafe-in-angu – amccausl

+2

amccausl拯救了新角度用户无数小时的调试由于角度“地狱文档”,ng-bind-html-unsafe已被弃用,请参考上面注释中的链接来解决答案。 – rjm226

2

因此,也许你想拥有这个在您的index.html加载库,脚本,以期初始化应用:

<html> 
    <body ng-app="yourApp"> 
    <div class="span12"> 
     <div ng-view=""></div> 
    </div> 
    <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script> 
    <script src="script.js"></script> 
    </body> 
</html> 

然后yourView.html可能仅仅是:

<div> 
    <h1>{{ stuff.h1 }}</h1> 
    <p>{{ stuff.content }}</p> 
</div> 

scripts.js可以让你的控制器的数据$ scoped到它。

angular.module('yourApp') 
    .controller('YourCtrl', function ($scope) { 
     $scope.stuff = { 
     'h1':'Title', 
     'content':"A paragraph..." 
     }; 
    }); 

最后,你必须配置的路由和分配控制器查看它的$范围(即你的数据对象)

angular.module('yourApp', []) 
.config(function ($routeProvider) { 
    $routeProvider 
    .when('/', { 
     templateUrl: 'views/yourView.html', 
     controller: 'YourCtrl' 
    }); 
}); 

我没有测试过这一点,对不起,如果有一个但我认为这是获取数据的角度方式

+0

如果我想要这种相同的行为但不依赖于routeProvider会怎么样? –

+0

它的使用界面路由器一样的,只是它的$ stateProvider而不是$ routeProvider和 .STATE( 'yourState',{ 网址: '/', templateUrl: 'yourView.html', 控制器: 'YourCtrl' }); – irth

3

您应该遵循Angular文档并使用$ sce - $ sce是一种为AngularJS提供严格上下文转义服务的服务。这里是一个文档:http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe

让我们与asynchroniously加载Eventbrite在线上售票登录按钮

在你的控制器的例子:

someAppControllers.controller('SomeCtrl', ['$scope', '$sce', 'eventbriteLogin', 
    function($scope, $sce, eventbriteLogin) { 

    eventbriteLogin.fetchButton(function(data){ 
     $scope.buttonLogin = $sce.trustAsHtml(data); 
    }); 
    }]); 

在你看来只是补充:

<span ng-bind-html="buttonLogin"></span> 

在你服务:

someAppServices.factory('eventbriteLogin', function($resource){ 
    return { 
     fetchButton: function(callback){ 
      Eventbrite.prototype.widget.login({'app_key': 'YOUR_API_KEY'}, function(widget_html){ 
       callback(widget_html); 
      }) 
     } 
    } 
}); 
49

为此,我使用自定义过滤器。

在我的应用程序:

myApp.filter('rawHtml', ['$sce', function($sce){ 
    return function(val) { 
    return $sce.trustAsHtml(val); 
    }; 
}]); 

然后,在视图中:

<h1>{{ stuff.title}}</h1> 

<div ng-bind-html="stuff.content | rawHtml"></div> 
+3

这不适合我。仍然变得原始html – chovy

+1

工作对我来说:-) –

+1

这是一个很好的解决方案@Daniel。如果我使用'$ sce.trustAsHtml',我不需要在应用程序模块中包含'ngSanitize'依赖项?我正在使用Angular 1.3 – Neel