AngularJS 的承诺 [英] AngularJS promise
问题描述
AngularJS 文档 说:
AngularJS docs say:
$q 承诺被模板引擎以 angular 识别,这意味着在模板中,您可以将附加到作用域的承诺视为结果值.
$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.
那么有人可以解释一下这个 fiddle 不起作用的原因吗?无法更改文本字段值.但是将 $http 服务返回到作用域字段的承诺分配给它就像一个魅力.
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.
控制器:
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">
推荐答案
需要在promise对象上使用then()函数:
You need to use the then() function on the promise object:
this.getItem().then(function(result) {
$scope.item = result;
});
就你而言,我认为你不需要承诺.Angular 的 $watch 系统会处理事情.只需在函数中返回一个对象,而不是原始类型:
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屋!