AngularJs embedding an MS Word doc using a $scope

2019-02-27 08:54发布

问题:

Embedding a random MS Word word doc, which I found on the internet, works if I hard code the 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>

However, I want to get the URL by AJAX, so I changed the HTML to

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

but even hardcoding that $scope variable in my JS:

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

gives

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

This seems quite basic - what am I doing wrongly?

回答1:

You should use $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);

and HTML:

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

Demo Fiddle


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

or:

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

doesn't work too because of policy, so you need pass through $sce full URL



回答2:

Here you need to import the angularjs predefined services:

$sanitize, $sce inject these in your controller and you can replace or redesign the url, beause of if you use directly it will not render that url, because it is one of the security policy to rendering the unwated thing on webpage,

In HTML:

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

In JS controller:

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);
});