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

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

2 Comments

How can I just access the rootScope, without requiring angular.element?
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...

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.