Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
share|improve this question

1 Answer 1

up vote 1 down vote accepted

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/

share|improve this answer
    
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.