簡體   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