Preventing flickering ngRepeat with promise in AngularJS

I have a set of objects, say Products, with which I can interact using $resource. On the index page, I would like to either display the collection, or, if the collection is empty, display a useful message. i.e.

In the controller

$scope.products = Products.query();

In the template

<div ng-repeat="product in products">
  ...
</div>

<div class="alert" ng-hide="products.length">
  <p>Oops, no products!</p>
</div>

This works great if the user does not look at the place where he will be ng-repeat. If they are, or there is a delay in the response from the server, they may notice a slight flicker before the promise is resolved.

Given that "calling the method of the $ resource object immediately returns a null reference" (see here ), such a flicker will always be an example in this. Instead, I write:

<div class="alert" ng-hide="!products.$resolved || products.length">
  <p>Oops, no products!</p>
</div>

. , , , Products. . - ? , ng-repeat (. ), , .

+4
2

:

Products.query(function(data) {
    $scope.products = data;
});

:

Products.query().$promise.then(function(data) {
   $scope.products = data;
});

, , .

+6

$promise $resource / .

, , .

/* products */
[
 { "id":1, "name":"name1" },
 { "id":2, "name":"name2" },
 ...
]
/***/

app.factory('Products', function ($resource) {
  return $resource('products.json'); 
});

, .

app.controller('MainCtrl', function ($scope, Products) {
  $scope.initialize = function () {
    $scope.products = null;
    Products.query().$promise.then(function (data) {
      $scope.products = data;
    });
  };

  $scope.initialize();
}); 

HTML , : ) ; b) ; c) ,

<body ng-controller="MainCtrl">
  <div ng-show="!products">
    Getting data... please wait
  </div>

  <div ng-show="products && products.length === 0">
    Oh noes!1 :( No products
  </div>

  <div ng-show="products">
    <span  ng-repeat="product in products">
      {{ product | json }} <br>
    </span>
  </div>

  <div>
    <button type="button" ng-click="initialize()">Refresh</button>
  </div>
</body>


plunker http://plnkr.co/edit/Ggzyz9

+1

All Articles