Tran Thien Chien
Tran Thien Chien

Reputation: 681

Angularjs - assign variable in callback function

I'm using controller as-syntax and met a ridicilous circumstance

this.showAddressDetail = false;
this.searchPlace = function() {
    GoogleService.searchPlace($('#address')[0], function(place) {
        this.showAddressDetail = true;
    });
};

whenever the callback of GoogleService.searchPlace be triggered. I want to assign true to this.showAddressDetail. But in this case this is the callback function.
So how to assign value to this.showAddressDetail?

Upvotes: 2

Views: 768

Answers (4)

Abdul23
Abdul23

Reputation: 6005

You can use a bind to call a function with a specific value of this in case that function is not called as a constructor.

var fn =  function(place) {
    this.showAddressDetail = true;
};
var callback=fn.bind(this);
this.showAddressDetail = false;
this.searchPlace = function() {
    GoogleService.searchPlace($('#address')[0],callback);
};

Upvotes: 1

Aides
Aides

Reputation: 3673

The this keyword by default refers to the owner of a function - not necessarily the place in code (reference).

To fix this simply store the controllers this in a local scope variable:

var vm = this;
vm.showAddressDetail = false;
vm.searchPlace = function() {
    GoogleService.searchPlace($('#address')[0], function(place) {
        vm.showAddressDetail = true;
    });
};

Common keywords for the local variable are vm (ViewModel), that, _this, self.

Upvotes: 1

A.B
A.B

Reputation: 20445

you can use this-that approach to save outer this context

var that = this;
that.showAddressDetail = false;
that.searchPlace = function() {
    GoogleService.searchPlace($('#address')[0], function(place) {
        that.showAddressDetail = true;
    });
};

Upvotes: 1

michelem
michelem

Reputation: 14590

You have to assign the "main" this to another variable:

var vm = this;
vm.showAddressDetail = false;
vm.searchPlace = function() {
    GoogleService.searchPlace($('#address')[0], function(place) {
        vm.showAddressDetail = true;
    });
};

Upvotes: 5

Related Questions