AngularJS-Render HTML嵌入代码作为布局

时间:2014-10-11 09:31:02

标签: html angularjs

我想问一下,我正在尝试制作一个简单的代码,用于渲染YouTube的嵌入共享代码,因为我使用ng-repeat来循环输入多个输入,但我似乎无法获得正确的渲染相反,我得到的是文字。我该如何将其变成正确的HTML输出?

以下是我作为示例制作的plunkr文件。

谢谢

2 个答案:

答案 0 :(得分:1)

像这样使用ng-bind-html:

  <body ng-app="videoGall">  
        <div ng-controller="topicVideoCtrl">
          <div ng-repeat="video in videos"><div ng-bind-html="makeTrust(video.url)"></div> </div>
        </div>
      </body>

videoGall.controller('topicVideoCtrl', function ($scope, $http,$sce) {  
    $scope.makeTrust=function(html){return $sce.trustAsHtml(html);};
    $scope.videos = [
      {"url":"<iframe width=\"560\" height=\"315\" src=\"\/\/www.youtube.com\/embed\/pbuGSt3Hb8k\" frameborder=\"0\" allowfullscreen><\/iframe>"},
                     {"url":"<iframe width=\"560\" height=\"315\" src=\"\/\/www.youtube.com\/embed\/y_o-ULSWWng\" frameborder=\"0\" allowfullscreen><\/iframe>"}];
});

答案 1 :(得分:1)

为此目的,我将以另一种方式对您的案例进行一些更改和处理: 已修复http://plnkr.co/edit/COnvjvoaYV643oQ46p9B?p=preview

<强> JS

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

app.config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    'self',
    'https://www.youtube.com/**'
  ]);
});

app.controller('videoController', ['$scope',
  function MyCtrl($scope) {

    $scope.product = {
      name: 'some name',
      description: 'some description',
      media: [{
        src: 'pbuGSt3Hb8k'
      },{
        src: 'y_o-ULSWWng'
      }]
    };

    $scope.getIframeSrc = function(src) {
      return 'https://www.youtube.com/embed/' + src;
    };
  }
]);

<强> HTML

<html ng-app="myApp">
<head>
  <script src="https://code.angularjs.org/1.2.1/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="videoController">
  <div ng-repeat="media in product.media">
    <div class="thumbnail">
      <div class="video-container">
        <iframe width="560" height="315" ng-src="{{getIframeSrc(media.src)}}" frameborder="0 " allowfullscreen></iframe>
      </div>
    </div>
  </div>
</body>    
</html>