Search code examples
javascriptangularjsabsolute-path

Image path in AngularJs


I have a image path in AngularJs $scope variable imageUrl, which comes from external source.

http://farm6.staticflickr.com/5579/14671096893_806ec359b7_m.jpg

I am trying to get the image on HTML page.

<img ng-src="{{imageUrl}}">

But when I am trying to run this in firefox, it is giving me error

"NetworkError: 403 Forbidden - http://localhost/demo/view/html/%5B%22http://farm6.staticflickr.com/5579/14671096893_806ec359b7_m.jpg%22%5D"

Its taking root path of project. How can I make some changes to show image on the web page?


Solution

  • If you look at the error that was generated, it contains some url encoded characters as well. I entered it into a Url Decoder and this is what the image url string actually looks like.

    http://localhost/demo/view/html/["http://farm6.staticflickr.com/5579/14671096893_806ec359b7_m.jpg"]
    

    Notice the bracket and quote characters?

    This leads me to believe that $scope.imageUrl contains the [""] symbols. You can easily test this out by rendering the value in a <pre> tag next to the <img> tag like so...

    <img ng-src="{{imageUrl}}">
    <pre>{{imageUrl}}</pre>
    

    If the value in the rendered <pre> tag has the [""] symbols, then the solution is to remove those symbols from the $scope.imageUrl property.

    You can remove these symbols from imageUrl like so...

    $scope.imageUrl = $scope.imageUrl.replace(/[\[\"\]]/g, "");
    

    However, if you're using the $http service to retrieve this data from the Flickr API, you should consider using the transformResponse option which allows you to manipulate data (in your case, strip out bad characters from the imageUrl) from an http request before resolving the promise.