Angularjs photo album

青春壹個敷衍的年華 提交于 2019-12-12 04:53:23

问题


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>

回答1:


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


来源:https://stackoverflow.com/questions/18730113/angularjs-photo-album

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!