0

I have an image handler which fetches the image byte stream from DB and returns a http response Content-Type: image/jpeg

In my angularjs app I would like to get the images and show them in a table. Here is the page code:

<tr ng-repeat="product in products>
  <td>
     <img ng-src="{{imageMaker(product.id)}}"/>
  </td>
</tr>

Controller code:

$scope.imageMaker = function (productId) {
    $http.get('/Handlers/ImageRenderer.ashx', {
        params: {
            id: productId
        }
    }).then(function (res) {
        return 'data:image/jpeg;base64,' + res.data;
    });
}

by running this code Chrome crashes. Any help would be appreciated.

Ryan
  • 615
  • 8
  • 19
  • is `res.data` base64 encoded already? – scniro Apr 15 '15 at 16:54
  • yes. I tried the following approach as well. http://stackoverflow.com/questions/16775729/angular-js-request-in-order-to-get-an-image – Ryan Apr 15 '15 at 17:09
  • have a look at this question pretty similar to your case http://stackoverflow.com/questions/29104607/angularjs-how-to-get-http-result-as-returned-value-of-a-function/29104867#29104867 – rakesh Apr 15 '15 at 17:30

2 Answers2

1

Your ng-src is set to the return of $scope.imageMaker. However, your implementation of that doesn't return anything (and thus returns undefined). Even if you were returning the promise, ng-src expects the expression to evaluate to a string which is then set as the src attr. It's not expecting a promise object that then eventually returns a string on success.

Personally, I'd either make a custom directive, when in the link function you go off and make your async call and then set the .src of the element on success.

.directive('myImg', function($http){
    return{
       scope:{imageId:'@myImg'},
       link: function(s,e,a){

            $http.get('/Handlers/ImageRenderer.ashx', {
                params: {
                    id: s.imageId
                }
            }).then(function (res) {
                e.src('data:image/jpeg;base64,' + res.data);
            });

      }  
    }
})

HTML:

<tr ng-repeat="product in products>
  <td>
     <img my-img="{{product.id}}"/>
  </td>
</tr>

As a side note base64 is ~30% less efficient than just using real image resources.

Dylan Watt
  • 3,357
  • 12
  • 16
0

This worked for me (based off of Dylan's answer):

.directive('myImg', function($http) {
    return {
        link: function(s, e, a) {
            $http.get('/Handlers/ImageRenderer.ashx', {
                params: {
                    id: s.imageId
                }
            }).then(function(res) {
                e[0].src = 'data:image/jpeg;base64,' + res.data;
            });
        }
    };
}