AngularJS promise

Raman Chodźka picture Raman Chodźka · Dec 29, 2012 · Viewed 24.2k times · Source

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">

Answer

asgoth picture asgoth · Dec 29, 2012

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();