eclaire211 eclaire211 - 2 months ago 15
AngularJS Question

Scoping issue with AngularJS

I am a bit of a javascript/angular newbie and am having some trouble understanding how the scope works. I have the following code that is not functioning due to scope issues:

Angular:

this.myFxn = function() {
var x = this.myModel; //this.myModel is set by an ng-model in the html
myService.myServiceFxn(x.Id)
.then(function (response) {
this.myModel = "";
});
};


I believe the issue is with my reference to this.myModel inside of the .then(). How can I correctly reference this variable without any scope issues?

Thank you for any help you can give! :)

Answer

Just keep the reference to the controller in a variable like the example with self

this.myFxn = function() {
    var self = this;
    myService.myServiceFxn(self.myModel.Id)
        .then(function (response) {
            self.myModel = "";
        });
};