0

EDIT: the following example doesn't do any useful work. It's just to illustrate my problem setting template variables from within img.onload. The actual image manipulation doesn't matter.

So I'm trying to convert an image to base64 as proposed in this answer and then adapt it for use in an angular project.

I can get the image encoded to base64, but then I can't get that data to appear in a template.

In my controller, I have the following:

vm.showInTemplate = "cluck";
var img = new Image();
img.src = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';
img.onload = function(){
    // logic removed for simplicity
    vm.showInTemplate= "moooo";
};

Then in the view, I have (for now):

{{ vm.showInTemplate }}

I know from Chrome console that vm.showInTemplate is available in img.onload() and I know that it is being set to "moooo", but in the template view, the value remains "cluck"

What am I doing wrong?

Community
  • 1
  • 1
crowhill
  • 2,398
  • 3
  • 26
  • 55
  • Since .onload is async, I guess you need to call an angular method to refresh the template. Sometime it's $scope.$apply() for $scope.property. It would help to know what "vm" is. – progysm Jun 20 '16 at 19:03
  • Yep. This is it. Thanks! – crowhill Jun 20 '16 at 19:12

2 Answers2

0

Why not try jQuery? bind know load image, iframe and other object. Look a example:

$(document).ready(function() {
 $('img#example').bind('load', function() { 
  console.log('load done'); 
 });
 $('button#load').click(function() { 
  $('img#example').attr('src','http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png');
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<img id="example" src="">
<button id="load">EXAMPLE</button>
KingRider
  • 2,140
  • 25
  • 23
0

Answer was obvious, thanks to progysm. Posting it here to save future generations a little time:

var url = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';
var img = new Image();
vm.showInTemplate= 'oink';
img.src = url;
img.onload = function(){
    $scope.$apply(function(){
        vm.showInTemplate = "mooo";
    });
};

The controller-as syntax confused me for a moment, but there's no reason not to use good ol' $scope here.

crowhill
  • 2,398
  • 3
  • 26
  • 55