mfrachet
mfrachet

Reputation: 8932

AngularJS, callback and variables scopes

I m actually facing a problem with javascript in general. In fact, I need to update a list after calling a callback in two different files.

This is my description of the callback :

 this.modify = function(){
    var self = this;
    var success = function(){
      self.user = self.userEdit;
    };

    var err = function(data){
      alert(data);
    };

    UserService.put(this.userEdit, success, err);
  }
}

And this is the function which calls the callback :

 UserService.put = function (data, succ, err) {
        var user = {login:data.login,nom:data.nom,prenom:data.prenom,password:data.password};
        $http({
            url: __ADRS_SRV__ + "user/"+data._id,
            method: "PUT",
            data:user,
            isArray: true
        }).success(function(data){
           succ();
        }).error(function(error){
            err(error);
        });
    }

In fact,

var success = function(){
      self.user = self.userEdit;
    };

doesn't seem to work properly, when I log self.user in the callback call, I got an undefined...

Do you have an idea to bypass this ?

Thanks for advance

Upvotes: 0

Views: 91

Answers (1)

runTarm
runTarm

Reputation: 11547

You have to remember the this as self before declaring the success function:

var self = this;
var success = function(){
  self.user = self.userEdit;
};

Or an alternative would be just using this, but bind the function with this variable:

var success = function() {
  this.user = this.userEdit;
}.bind(this);

Hope this helps.

Upvotes: 1

Related Questions