From a technical standpoint, the issue at hand is not specific to AngularJS but rather a characteristic of javascript
Essentially, functions defined within a scope have access to local variables and parameters from their parent scope
function parent(arg){
var local
function child(){
// can access arg and local here
}
}
The concept of scope is akin to a parent-child relationship: just like how as a parent you are willing to share your cookie with your children, but as a kid, your cookie is strictly yours and off limits to your parent :). Put simply, inner scope can reach outer scope, but not vice versa
So yes, you should be able to:
$http.get('/plugin/' + key + '/js').success(function (data) {
if (data.length > 0) {
console.log(data, key); //if passed as an argument to $http.get
//it can be accessed here
}
});
Furthermore, due to javascript's event-driven nature, inner functions retain references to outer function’s variables. This may sound familiar
In javascript, functions are objects
Local variables and parameters are treated as private members of the function:
function ObjectA(){ // constructor definition
var x = 10 // private variable
changeX : function(){
x = 20 // access and MODIFY a parent scope variable
}
}
Understanding how private variables function in javascript essentially entails grasping the idea of closure. Hence, for callback functions, it's probable that by the time they are executed, the value of the parent scope variable might have changed. To address this, one can employ an Immediately Invoked Function Expression (IIFE)
$http.get('/plugin/' + key + '/js').success((function(currentKeyValue) {
return function(data) {
console.log(currentKeyValue, data);
// currentKeyValue serves as a REFERENCE to the outer function's parameter.
// While String is passed by value in javascript, the currentKeyValue of the outer scope is a DISTINCT string that holds the same value as KEY upon invocation
}
})(key)); // immediate invocation of the function passing the key as a parameter