jwvanderbeck
jwvanderbeck

Reputation: 67

Pass var to angular $resource success function

I've been going crazy over this and I think the answer is probably out there but I don't know the right way to ask Google the question.

Essentially I need a way to make a $resource call, and pass in some data that I want to then use in the success function.

app.controller('VariantListController', ['djResource', function(djResource){
    var Variants = djResource('/ship-builder/variants/?format=json');
    var Vehicle = djResource('/ship-builder/vehicles/:id', {id: '@id'});
    this.variants = Variants.query(function(variants){
        $(variants).each(function(){
            console.log(this);
            variantData = this;
            var vehicleData = Vehicle.get({id:this.baseVehicle}, function(){
                console.log(variantData);
            })
        })
    });

}]);

In the above example, in the innermost success function, 'variantData' is always the value of the LAST entry from the previous level. This makes sense because the value was set by the last item in the array long before the success happens. I need a way though to have the value of the 'variantData' that was inexistince when the Vehicle.get() was called.

Does that make sense? I find it very hard to explain the issue.

Upvotes: 1

Views: 187

Answers (3)

Jonathan Fingland
Jonathan Fingland

Reputation: 57167

Since the value in variantData may change before the success callback is actually called, you want to ensure the the callback has the original value stored.

var vehicleData = Vehicle.get({id:this.baseVehicle}, function(vData){
     return function() {
          console.log(vData);
     }
}(variantData));

The above will create a new function with variantData stored in a closure.

Upvotes: 0

Chandermani
Chandermani

Reputation: 42669

You need to create a closure to make it work. Something like

this.variants = Variants.query(function(variants){
        $(variants).each(function(){
            getVehicleData(this);
        })
    });

function getVehicalData(variantData) {
   var vehicleData = Vehicle.get({id:variantData.vehicleId}, function(){
                console.log(variantData);
            })
}

Upvotes: 2

Joe
Joe

Reputation: 2596

I am by no means an expert on the $resource service, but perhaps using the $promise.then method instead of the success callback would work.

$(variants).each(function(){
  console.log(this);
  variantData = this;

  Vehicle.get({id:this.baseVehicle}).$promise.then(function() {
    console.log(variantData);
  });
});

Upvotes: 0

Related Questions