-3

I am using angularjs/javascript code for image Uploading but i got stuck in variable binding , can anyone help me out, here is my code.

var image_source;
$scope.uploadedFile = function(element) {
  reader.onload = function(event) {
  image_source = event.target.result;
  $scope.$apply(function($scope) {
    $scope.files = element.files;
  });
}
console.log(image_source,event.target.result, element.files[0],  "***not working here***");

I'm binding varibale named image_source within function but when i access this outside the function it always return undefined why ?

PS:- i can get this in the typescript using phatarrow operator but how to do in javascript i dont know

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215

1 Answers1

-1

If your console.log statement is called before $scope.uploadedFile which is most likely to be the case, the value will not be set, I suggest you try to call the function and put your console.log statement at the end of the function, inside the block.

That's not an angular issue but more like javascript, when you declare an anonymous function it's not called immediately

let mynumber = 1
let myfunction = () => { 
    mynumber = 2
}
console.log(mynumber) // 1
myfunction()
console.log(mynumber) // 2
Sami Triki
  • 408
  • 3
  • 7
  • yes i know but i have to console outside from the fuction in some case – Pardeep Jain Jun 08 '17 at 11:50
  • I'm not sure it's useful, I assume that the chunk of file that you're showing here is your controller? You just can't put your console log statement before a function sets the value and then expect it to be set – Sami Triki Jun 08 '17 at 11:51
  • so what should i do ? – Pardeep Jain Jun 08 '17 at 11:53
  • It depends on what you want to acheive, if your console.log statement is only intended for inspecting the variable's value when it's set then just put a debugger statement and check it in the browser – Sami Triki Jun 08 '17 at 11:55
  • but always console statement runs before function, so what to do in that case ? – Pardeep Jain Jun 08 '17 at 11:56
  • Do you realise that you are declaring a callback that is not called and then expect to be able to access the value immediately, before the value is set? it's just plain javascript – Sami Triki Jun 08 '17 at 11:57
  • yes, i know , that's why i put this as question and ask for alternate or correction – Pardeep Jain Jun 08 '17 at 11:58
  • Just call `$scope.uploadedFile()` **before** your `console.log`, obviously, as @SamiTriki tried to tell you. – SinDeus Jun 08 '17 at 13:01