2

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?

4 Answers 4

5

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;
    });
};
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.