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
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();
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.
Its like @Mark said, here you can find a Working Example of your snippet.
Basically you were returning an object and not binding the model itself.
$timeout(function(){
$scope.item = {
title: 'Some title'
}; // Apply the binding
deferred.resolve(); // Resolve promise
},2000); // wait 2 secs