andyhasit
andyhasit

Reputation: 15319

Can you bind a promise to a scope property in Angular?

On this blog I read:

...note that we are storing a promise to the scope. This is not the same as the actual list. AngularJS automatically resolves this as the actual returned list and presents it in the generated HTML.

Does this mean I can do this:

angular.module('app', []).service('Data', function($q) {
  return {
   getItems: function() {
     return $q.when(['cat', 'dog']);
   }
  }
})
.controller('MyController', function(Data, $scope) {
  $scope.items = Data.getItems();
});

Instead of this?

.controller('MyController', function(Data, $scope) {
   Data.getItems().then( function(result) {
     $scope.items = result;
   });
});

If so, where is the documentation for it? I've searched through the docs to no avail.

I tried in a plunkr but got nowhere.

I also found this SO question that mentions the async directive. Again, I struggle to find any documentation on this.

Am I confusing Angular1 with Angular2?

Upvotes: 1

Views: 1574

Answers (2)

Noel
Noel

Reputation: 3556

You used to be able to do that with Angular 1.2 (which, seems to have been a mistake). 1.3 and newer requires you to unwrap the promise before binding.

Edit: This question may be a duplicate Angular JS: how to bind to promises

Upvotes: 1

Mathew Berg
Mathew Berg

Reputation: 28750

Maybe? You can access the values in your plunkr like this if you want:

i in items.$$state.value

Here's an updated plunkr that will simulate a http request via a timeout:

https://plnkr.co/edit/aWfDWJWIJnsnXLpTEIol?p=preview

Upvotes: 1

Related Questions