[英]Can't access global variables in angular JS?
根據這個問題: 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
}])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.