Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS promise

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">
like image 721
Raman Chodźka Avatar asked Dec 29 '12 08:12

Raman Chodźka


2 Answers

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();
like image 62
asgoth Avatar answered Oct 09 '22 15:10

asgoth


I believe the reason your first fiddle does not work is because you are essentially binding scope property item to a promise. When you attempt to alter the value by typing into the text field, angular notices the activity, and then reassigns/resets the value of item to the result of the promise (which hasn't changed).

The solution provided by @asgoth sets/assigns the value of item once, when the promise is resolved. There is no binding going on here (i.e, item is not bound to the promise), so altering the value via the textbox does alter the value.

like image 24
Mark Rajcok Avatar answered Oct 09 '22 13:10

Mark Rajcok