1

I am trying to save the text from a file into a string inside the rootscope. What I have so far is a directive, which loads properly, and a function which checks the root

function callData($rootScope) {
    console.log("function working");
    console.log($rootScope.data);
}

angular.module('spreadsheetApp').directive('fileReader', function($rootScope) {
    return {
        restrict: 'E',
        scope: true,
        templateUrl:'views/fileReaderTemplate.html',
        controller: 'fileReaderController',
        link: function (scope, element, attributes, controller) {
            $element.bind("change", function(event) {
                var files = event.target.files;
                var reader = new FileReader();
                reader.onload = function() {
                    $rootScope.data = this.result;
                    console.log($rootScope.data);
                    callData($rootScope.data);
                    console.log("55");
                };                
                reader.readAsText(files[0]);
            });
        } 
    }    
});

Which returns the following ouput for a textfile that says:

# Text file
Hello, world!

Output:

Hello, world!
function working 
fileDirective.js:44
Uncaught TypeError: Cannot read property 'data' of undefined fileDirective.js:45
callData fileDirective.js:45
reader.onload
user1876508
  • 12,864
  • 21
  • 68
  • 105

1 Answers1

1

Since you're trying to access the scope outside the function, this requires some extra actions.

The answer to your question has already been answered here: AngularJS access scope from outside js function

You need to use this code:

 var scope = angular.element($("#yourelement")).scope();

cfr.: http://jsfiddle.net/arunpjohny/sXkjc/8/

Community
  • 1
  • 1
Kristof Feys
  • 1,822
  • 1
  • 19
  • 36
  • How can I just access the rootScope, without requiring angular.element? – user1876508 Jul 17 '13 at 21:28
  • 1
    As you want to pass the rootscope in the function, you'll need to do callData($rootScope); instead of callData($rootScope.data); because what you're now trying to do in callData function is actually $routScope.data.data which doesn't exist, hence the error... – Kristof Feys Jul 17 '13 at 21:48