0

In my angularjs application, I have the following block which is behaving weirdly.

I have declared the variable in the function block but unable to access the values in spite of setting the value inside the function block. Where I am going wrong.

$scope.submitForm = function (isValid) {
   var file = $scope.myFile;
   var contents;
   $scope.dataObj;
   if (file) {
       var r = new FileReader();
       r.onload = function (e) {
         console.log('Inside the file function ....');
         contents = e.target.result;
         $scope.$apply(function () {
           $scope.fileReader = contents;
           contents = contents.replace(/\r\n+/g, ",");
           $scope.dataObj = {hosts: contents};
           console.log($scope.dataObj); // prints the value twice
         });
       };
        r.readAsText(file);
   }
   console.log("Printing the data objects .... ");
   console.log($scope.dataObj); // prints undefined
}
rrk
  • 15,677
  • 4
  • 29
  • 45
zilcuanu
  • 3,451
  • 8
  • 52
  • 105
  • Are you asking why console.log($scope.dataObj); prints undefined outside if (file) {...} ? – J.D. Feb 22 '16 at 12:51
  • Yes. console.log($scope.dataObj); is printing undefined. As far as I understand, in javascript we have the function scope. so even if the variable is defined at the top of the function, if we set the value, we should be able to get the last value after the assignment. – zilcuanu Feb 22 '16 at 12:53

3 Answers3

2

$scope.$apply will executed in a later cycle as your code. So $scope.dataObj will be undefined (because of the initialization '$scope.dataObj;') and $scope.$apply will run after the current diggest cycle.

I dont know what you wanna do after the assignment, but maybe a watcher will help you?

$scope.$watch('dataObj', function(){
   console.log($scope.dataObj);
});

More information about angular lifecycle: http://onehungrymind.com/notes-on-angularjs-scope-life-cycle/

Develobba
  • 716
  • 8
  • 22
1

at the time of the last console.log($scope.dataObj) there's no guarantee that onload has already been fired.

readAsText is async (Why is FileReader.readAsText() returning null?) which implies that submitForm is left before onload has triggered.

Community
  • 1
  • 1
Daniel Nachtrub
  • 366
  • 1
  • 6
1

Like CodeNashor said, in your line of code you defined r.onload function and made the assignment inside of that function, but r.onload is executed after console.log($scope.dataObj); // prints undefined.

J.D.
  • 1,145
  • 2
  • 15
  • 29
  • the onload-function is not the problem. Even without it, the $apply-Cycle is not over till the console.logs fired. $watch or $timeout will help. – Develobba Feb 22 '16 at 12:58