Glenn Dayton Glenn Dayton - 4 months ago 14
JSON Question

AngularJS promise not setting "this" properly

I'm attempting to pre-populate a select list with data from a JSON file.

Controller

this.langs = [];
var promise = $lcidFactory.getLCIDS();
promise.then(
function(payload){
this.langs = payload.data;
console.log(payload.data);
},
function(error){
alert("[Error] "+error);
}
);


When I review the console with the inspector the data appears. However, the following code produces an empty JSON,
{}
.

HTML

<template-editor-form model="cpCtrl.data">
...
<pre>{{ cpCtrl.langs | json }}</pre>
...
</template-editor-form>


If I set
this.langs = []
in line 1 of the controller to
this.langs = ["one"]
the template reflects the changes properly, as
["langs": ["one"]]


EDIT
This question is similar to How does the "this" keyword work?, however it addresses one of the common pitfalls of the usage of
this
in the context of AngularJS, in a concise fashion.

Answer

Well, i guess your problem is that "this" in your function is not the same "this" outside the function. You could set the "outside this" to a variable, so you can use that variable to access your langs even in the callback function.

var self = this;
this.langs = [];
var promise = $lcidFactory.getLCIDS();
promise.then(
    function(payload){
        self.langs = payload.data;
        console.log(payload.data);
    },
    function(error){
        alert("[Error] "+error);
    }
);