AngularJs 使用 $scope 变量作为 URL 嵌入 MS Word 文档

AngularJs embedding an MS Word doc using a $scope variable as the URL

嵌入我在互联网上找到的随机 MS Word 文档,如果我硬编码 URL:

<iframe src="http://docs.google.com/gview?url=https://d9db56472fd41226d193-1e5e0d4b7948acaf6080b0dce0b35ed5.ssl.cf1.rackcdn.com/spectools/docs/wd-spectools-word-sample-04.doc&embedded=true"></iframe>

但是,我想通过AJAX得到URL,所以我把HTML改成了

<iframe src="{{cvUrl}}&embedded=true"></iframe> 

但甚至在我的 JS 中硬编码 $scope 变量:

$scope.cvUrl = 
    'http://docs.google.com/gview?url=https://d9db56472fd41226d193-1e5e0d4b7948acaf6080b0dce0b35ed5.ssl.cf1.rackcdn.com/spectools/docs/wd-spectools-word-sample-04.doc';

给出

Object not found!

The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404

localhost
Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.6.24

这看起来很基本 - 我做错了什么?

你应该使用 $sce.trustAsResourceUrl

var cvUrl = 
'http://docs.google.com/gview?url=https://d9db56472fd41226d193-1e5e0d4b7948acaf6080b0dce0b35ed5.ssl.cf1.rackcdn.com/spectools/docs/wd-spectools-word-sample-04.doc&embedded=true';

$scope.cvUrlTrusted = $sce.trustAsResourceUrl(cvUrl);

和HTML:

<iframe ng-src="{{cvUrlTrusted}}"></iframe>

Demo Fiddle


<iframe src="{{cvUrl}}&embedded=true"></iframe> <!-- wrong syntax -->

或:

<iframe ng-src="{{cvUrlTrusted + '&embedded=true'}}"></iframe>

由于政策原因不太有效,因此您需要通过 $sce 完整 URL

这里需要导入angularjs个预定义服务:

$sanitize, $sce 将这些注入到你的控制器中,你可以替换或重新设计 url,因为如果你直接使用它不会渲染 url,因为它是在网页上呈现未处理内容的安全策略之一,

在HTML中:

 <iframe ng-src="{{urlHere}}"></iframe>

在 JS 控制器中:

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

app.controller('Ctrl', function($scope, $sanitize, $sce) {
  var Url = 
    'http://yoururl.com.doc&embedded=true';

  $scope.urlHere= $sce.trustAsResourceUrl(Url);
});