1

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.

3

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.