根据此问题:Global variables in AngularJS

设置全局变量的方法是通过服务或rootscope。

但是我发现,除非将工厂传递给函数,否则无法访问函数中的全局变量。如果变量不在函数中,该如何访问?我需要这样做的原因是因为我无法控制从另一个库中使用的回调函数的参数。

例如,如果我的工厂是这样的:

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


我想访问我可以执行的函数中的主体

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


但是如果我不控制回调函数的参数...

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


如何在此回调函数中访问主体?

最佳答案

只要确保在有权访问主体的块范围内定义onNotificationCallback

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

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

    //do something with onNotificationCallback

}])

07-24 09:50
查看更多