AngularJS承诺 [英] AngularJS promise

查看:156
本文介绍了AngularJS承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AngularJS文档


  

$ Q许通过在角模板引擎,这意味着,在模板中,你可以把连接到一个范围的承诺,好像他们是所得的值识别。


所以可能有人请解释原因,这小提琴不工作?这是不可能更改文本字段值。但是,$ HTTP服务返回到范围场就像一个魅力分配的承诺。

控制器:

 函数myController的($范围,$ Q $超时){
    this.getItem =功能(){
        变种推迟= $ q.defer();
        deferred.resolve({
            标题:有些标题
        });
        返回deferred.promise;
    };    $ scope.item = this.getItem();
}

HTML:

 <输入类型=文本NG模型=item.title>


解决方案

您需要使用则()函数的承诺对象:

  this.getItem()。然后(功能(结果){
   $ scope.item =结果;
});

在你的情况,我不认为你需要一个承诺。角的$观测系统将处理后事。 就在你的函数返回一个对象,而不是原始类型

  this.getItem =功能(){
    变种项= {};    //做一些异步的东西
    $ http.get(...)。成功(功能(结果){
       item.title =结果;
    });
    归还物品;
};$ scope.item = this.getItem();

AngularJS docs say:

$q promises are recognized by the templating engine in angular, which means that in templates you can treat promises attached to a scope as if they were the resulting values.

So could someone please explain the reason this fiddle not working? It's not possible to change text field value. But assigning promises that $http service returns to a scope field works like a charm.

Controller:

function MyController($scope, $q, $timeout) {
    this.getItem = function () {
        var deferred = $q.defer();
        deferred.resolve({
            title: 'Some title'
        });
        return deferred.promise;
    };

    $scope.item = this.getItem();
}

Html:

<input type="text" ng-model="item.title">

解决方案

You need to use the then() function on the promise object:

this.getItem().then(function(result) {
   $scope.item = result;
});

In your case I don't think you need a promise. Angular's $watch system will take care of things. Just return an object in your function, not a primitive type:

this.getItem = function () {
    var item = {};

    // do some async stuff
    $http.get(...).success(function(result) {
       item.title = result;
    });
    return item;
};

$scope.item = this.getItem();

这篇关于AngularJS承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆