Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  90] [ 7]  / answers: 1 / hits: 23997  / 12 Years ago, fri, february 15, 2013, 12:00:00

I have a scope like $scope.doc_details in my angularjs controller, and I want to use it to display a pdf file by using a tag, like this:



<object data={{doc_details.file_url}} type=application/pdf></object>


but it doesn't get loaded in the browser, in my chrome console, all I see is:



Failed to load resource: the server responded with a status of 404 (Not Found) 
http://localhost/%7B%7Bdoc_details.file_url%7D%7D


and when I just display it using <span>{{doc_details.file_url}}</span> it show the value.


More From » html

 Answers
65

The problem here is that the browser is seeing



<object data={{doc_details.file_url}} type=application/pdf></object>


in the DOM before Angular compiles it, and obviously {{doc_details.file_url}} isn't a valid URL.



Directives can be your friend here.



Say we want to write:



<pdf src='doc_details.file_url'></pdf>


We can create a directive:



app.directive('pdf', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
var url = scope.$eval(attrs.src);
element.replaceWith('<object type=application/pdf data=' + url + '></object>');
}
};
});


This will defer the creation of the object element until we actually have the URL available to us from the scope (assuming it's already there - otherwise you'd want to $watch the src attribute on the scope until it became available).



Here this is in a fiddle.


[#80199] Thursday, February 14, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynkarinam

Total Points: 740
Total Questions: 103
Total Answers: 103

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;