How to pass a value to an AngularJS $http success callback

前端 未结 5 931
旧时难觅i
旧时难觅i 2020-12-31 04:54

In my AngularJS application I am doing the following

$http.get(\'/plugin/\' + key + \'/js\').success(function (data) {
    if (data.length > 0) {
                 


        
5条回答
  •  温柔的废话
    2020-12-31 05:22

    Technically speaking, this is not an AngularJS problem but a feature of javascript

    first of all, functions that you defined inside a scope will have access to local variable and parameter of its parent scope

    function parent(arg){
       var local
       function child(){
           // have access to arg and local
       }
    }
    

    Scope actually works well with the parent-child analogy: if you are the parent and you own a cookie, of cause you are welling to share it with your children...but if you are a kid...your cookie is your cookie, your parent is not allowed to touch it :). In other words, inner scope can access outer scope but it does not work both ways

    So you should definitely be able to do:

    $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
        }
    });
    

    Secondly, because of the event-driven nature of javascript, inner function store references to the outer function’s variables. you probably have heard of this

    functions in javascript are objects

    local variables and parameters are thus private members of the function:

    function ObjectA(){ // define a constructor
        var x = 10      // private variable
        changeX : function(){
                      x = 20   // access and MODIFY a variable of parent scope
                  }
    }
    

    if you can understand how private variable works in javascript, then you basically understand what closure is. Thus, for call back function, it is very possible that by the time it is triggered, the value of the parent scope variable is already changed. To fix this, you can use an Immediately Invoked Function Expression (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
    

提交回复
热议问题