从技术上讲,这不是 AngularJS 的问题,而是 javascript
的一个特性
首先,您在作用域中定义的函数将可以访问局部变量和参数其父范围
function parent(arg){
var local
function child(){
// have access to arg and local
}
}
Scope 实际上适用于父子类比:如果您是父母并且您拥有一个 cookie,那么您当然愿意与您的孩子分享它......但如果您是一个孩子...你的 cookie 是 你的 cookie,你的父母不能碰它 :)。换句话说,内部作用域可以访问外部作用域,但它不能双向工作
所以你肯定可以做到:
$http.get('/plugin/' + key + '/js').success(function (data) {
if (data.length > 0) {
console.log(data, key); //as long as you can pass it to $http.get as an argument
//you can access it here
}
});
其次,由于 javascript 的事件驱动特性, inner function store references to the outer function’s variables。你可能听说过这个
javascript 中的函数是对象
因此,局部变量和参数是函数的私有成员:
function ObjectA(){ // define a constructor
var x = 10 // private variable
changeX : function(){
x = 20 // access and MODIFY a variable of parent scope
}
}
如果你能理解私有变量在javascript中是如何工作的,那么你就基本理解了闭包是什么。因此,对于回调函数,很可能在它被触发时,父范围变量的值已经改变了。要解决此问题,您可以使用立即调用函数表达式 (IIFE)
$http.get('/plugin/' + key + '/js').success((function(currentKeyValue) {
return function(data) {
console.log(currentKeyValue, data);
// again, currentKeyValue is a REFERENCE to outer function's
// parameter. However, since String is passed by value in javascript
// currentKeyValue of outer scope is a DIFFERENT string that has the
// same value as KEY when it is invoked
}
})(key)); // immediately invoke the function passing the key as a parameter