0

I'm trying to figure out the best to handle working with async data.

Basically, I receive data to my controller doing:

 UserResource.query(function (res) {
      $scope.user = res;
 });

This works fine, but there's flickering. For example, if I'm using this along with another directive (such as bootstrap select), it will render the select first (with no data), then it will show it correctly.

Is there an elegant way to handle this, without creating lots of additional parameters simply to check values and do show/hides with an ng-switch.

Any tips/best practice suggestions would be great!

Thank you

dzm
  • 22,844
  • 47
  • 146
  • 226
  • It looks like resource has promises in it, so it seems that using `.$then(function(){});` would do the trick? Then I can do an `ng-switch on="dataAfter$then"` – dzm May 13 '13 at 01:38
  • I think this depends on what version of angular. The stable version's resource I don't believe returns a promise. http://stackoverflow.com/questions/15299850/angularjs-wait-for-multiple-resource-queries-to-complete – lucuma May 13 '13 at 02:36
  • I recently ran into this problem. You need to use their `$promise` PR commit which is a feature slated for 1.1.3. Solution here: http://stackoverflow.com/questions/16429832/callback-after-async-foreach-angularjs/16447884#16447884 – Dan Kanze May 13 '13 at 05:22

1 Answers1

0

Using the $resource promise PR commit slated for 1.1.3

$scope.userResource = function() {
    var promise = UserResource.get().$promise.then(
        function( res ){
            $scope.user = res;
        },
        function( error ){
            //Something went wrong!
        }
    )
    return promise;
}

Ran into this myself recently: callback after async forEach AngularJS

Edit:

@dave Had a good catch --- that is, in 1.1.4 this convention changes too:

UserResource.get().$then() ...

$then is returned on the $resource object directly.

Community
  • 1
  • 1
Dan Kanze
  • 18,485
  • 28
  • 81
  • 134
  • I'm using 1.1.4 - Looks like you just do `UserResource.query().$then()`, instead of `$promise.then` – dzm May 13 '13 at 14:03
  • @dave Good catch --- Was unaware of 1.1.4 convention. So it just becomes `var promise = UserResource.get().$then(` ? – Dan Kanze May 13 '13 at 14:04
  • Exactly, same syntax but `$then` is returned on the `$resource` object directly. – dzm May 13 '13 at 14:07