繁体   English   中英

如何使用AngularJS模板渲染html

[英]How to render html with AngularJS templates

这是我的模板:

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

这是我的视图模板:

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

{{stuff.content}}

我得到的content为html,我想在视图中显示,但我得到的只是原始的HTML代码。 我该如何呈现该HTML?

使用-

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

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

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

在我的应用程序:

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>

你应该遵循Angular文档并使用$ sce - $ sce是一种为AngularJS提供Strict Contextual Escaping服务的服务。 这是一个文档: http ://docs-angularjs-org-dev.appspot.com/api/ng.directive: ngBindHtmlUnsafe

让我们以异步加载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);
            })
      }
    }
});

在angular 4+中,我们可以使用innerHTML属性而不是ng-bind-html

在我的情况下,它正在工作,我正在使用角5

<div class="chart-body" [innerHTML]="htmlContent"></div>

In.ts文件

let htmlContent = 'This is the `<b>Bold</b>` text.';

因此,您可能希望在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可以为你的控制器提供数据$ scope'd。

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

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

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

我没有测试过这个,抱歉,如果有错误,但我认为这是获取数据的Angularish方式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM