AngularJS承诺

Ram*_*źka 10 angularjs angular-promise

AngularJS文档:

$ q promises被临界引擎识别为angular,这意味着在模板中,您可以将附加到范围的promise视为结果值.

那么有人可以解释一下这个小提琴不起作用的原因吗?无法更改文本字段值.但是,分配$ http服务返回到范围字段的承诺就像魅力一样.

控制器:

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

    $scope.item = this.getItem();
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<input type="text" ng-model="item.title">
Run Code Online (Sandbox Code Playgroud)

asg*_*oth 14

您需要在promise对象上使用then()函数:

this.getItem().then(function(result) {
   $scope.item = result;
});
Run Code Online (Sandbox Code Playgroud)

在你的情况下,我认为你不需要承诺.Angular的$ watch系统将负责处理事情.只返回函数中的对象,而不是原始类型:

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

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

$scope.item = this.getItem();
Run Code Online (Sandbox Code Playgroud)