-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

11
  • where you had declared image_source?? Commented Jun 8, 2017 at 11:47
  • try declaring it outside of the scope Commented Jun 8, 2017 at 11:47
  • i have declared outside the function Commented Jun 8, 2017 at 11:48
  • 1
    File operation is Async operation. You are assigning value to image_source inside onload method. It may be the reason for not working Commented Jun 8, 2017 at 11:49
  • 1
    its function-scoped, not sure why u r expecting it to be accessible outside. fat-arrow function gets the scope of the parent-block and hence it might work in es6. r u expecting block-scope in es5?? that wont work. Commented Jun 8, 2017 at 11:50

1 Answer 1

-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
Sign up to request clarification or add additional context in comments.

8 Comments

yes i know but i have to console outside from the fuction in some case
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
so what should i do ?
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
but always console statement runs before function, so what to do in that case ?
|

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.