user1424508
user1424508

Reputation: 3301

Angularjs photo album

Hi I'm making a photoalbum app with angularjs which grabs base-64 encoded image strings from my server and decodes them into images.

The problem is my angularjs app can't seem to decode the base64 strings. On my template it shows the no image found icon. I checked the base64 strings and its fine when I embed it straight to the template like this:

 <p><img src="data:image/jpeg;charset=utf-8;base64, /9j/4AAQSkZJRgABAQEBLA...etc.</p>'

The image will show up. However I need to grab the photoalbum data from a service within my customer directive (code below).

Can anybody help with this problem?

Here is my code:

directive.js

 .directive('photoalbumsDisplay', ['$compile', 'myprofileService', function($compile,       
 myprofileService) {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            myprofileService.retrieve_albums().then(function(data) {
                var html = [];
                for (var p = 0; p < data.length; p++) {
                    //album photos array
                    var pic = data[p];

                    html += '<p><img src="data:image/jpeg;base64, ' + pic + '"/></p>';
                }

                element.replaceWith(html)


            });
        }
    }
}]);

template.html

 <div data-ng-controller="photogalleryCtr" data-ng-init="init()">

    <photoalbums-display></photoalbums-display>

</div>

Upvotes: 0

Views: 2875

Answers (1)

Ian Wilson
Ian Wilson

Reputation: 9059

You might try using ng-src instead of src and getting photos from the scope in your directive instead of getting them inside your directive:

http://docs.angularjs.org/api/ng.directive:ngSrc

Then you can do this in your markup:

<photoalbums-display="photos"></photoalbums-display>

And change your directive like this:

app.directive('photoalbumsDisplay', function () {
    return {
        restrict: 'E',
        scope: {
            photos: '=photos'
        },
        template: '<p ng-repeat="photo in photos">' +
            '<img ng-src="data:image/jpeg;base64, {{photo.data}}"></p>'
    };
});

And add this to your controller, with the necessary injections:

$scope.photos = [];
myprofileService.retrieve_albums().then(function(data) {
    var i, length;
    for (i = 0, length = data.length; i < length; i += 1) {
        $scope.photos.push({
            data: data[i]
        });
    }
});

Upvotes: 1

Related Questions