AngularJS - 将回调结果设置为控制器变量

时间:2018-03-08 16:22:14

标签: javascript angularjs asynchronous events

我有一个事件,声明如下:

event.watch(function (error, result) {
    // result will contain various information
    // including the arguments given to the `Person`
    // call.
    if (!error) {
        console.log(result);
    } else {
        console.log(error);
    }
});

如果我尝试将变量的结果分配给变量,如下所示:

vm.fName = result.fName;

然后将变量记录在事件回调函数之外,在控制台中将显示undefined。如果我在事件中记录变量,则显示正确的值。 根据我的理解,这是一个异步调用,在事件结束之前将调用console.log(vm.fName);,并且UI中显示的值为空,因为它未定义。

我需要将结果存储在变量中,并使用将其进一步绑定到我的ng-models。 我尝试了很多解决方法,但似乎没有一个工作。 任何帮助表示赞赏。谢谢!

### EDIT 以下是正在发生的事情的一个例子:

var response = {};

setTimeout(function () {
    response = {
        "fName": "John",
        "age": 22
    };
    console.log(response);
}, 2000);

console.log(response);

如果运行此示例,您将看到在异步调用之前将调用最终的console.log。 因此,返回给UI的值将是一个空对象{}。 通话结束后,响应将如下所示:

response = {
            "fName": "John",
            "age": 22
        };

但是在UI中已经显示了空对象。 在设置变量之前,我需要一种等待异步调用完成的方法。

0 个答案:

没有答案