Terence Chow
Terence Chow

Reputation: 11153

Can't access global variables in angular JS?

According to this question: Global variables in AngularJS

the method of setting global variables is through a service or rootscope.

However I'm finding that I can't access the global variable in a function, unless I pass the factory into my function. How can I access the variable if it's not in a function? The reason I need to do this is because I don't control the parameters of callback functions that I use from another library.

For example, if my factory is like this:

.factory('principal',[$q, ...etc etc function($q ...){
    return{
           a_variable: 'an_example'
    }
 ]})

and I want to access principal in a function I can do

function example_function(principal){
    puts principal.a_variable //works!
}

But if I don't control the parameters of callback functions...

function onNotificationCallback(result){
     // this function is provided to me but principal isn't a parameter
     // therefore principal.a_variable is not accessable!
}

How do I access principal in this callback function?

Upvotes: 0

Views: 310

Answers (1)

Amit Portnoy
Amit Portnoy

Reputation: 6336

just make sure you define onNotificationCallback in a block scope that has access to principal

angularModule./*controller/Service/factory..*/('myThing', ['principal', function(principal) {

    onNotificationCallback = function(result) {
        //principal is available here
    };

    //do something with onNotificationCallback 

}])

Upvotes: 1

Related Questions