Question

I have an AngularJS template that looks like this:

<table data-ng-switch data-on="data.length">
    <tbody data-ng-switch-when="0">
        <tr>
            <td>No data available.</td>
        </tr>
    </tbody>
    <tbody data-ng-switch-default>
        <tr data-ng-repeat="row in data">
            <td>{{row.name}}</td>
        </tr>
    </tbody>
</table>

My controller and factory look like this:

demo.factory('Demo', function($resource) {
    return $resource('data.json');
});

demo.controller('DemoController', ['$scope', '$state', '$stateParams', 'Demo', function($scope, $state, $stateParams, Demo) {   
    $scope.data = Demo.query();
}]);

Is there a way to prevent "No data available." from flashing on the screen quickly before the data is retrieved from the resource?

Était-ce utile?

La solution

The reason this is happening is because the $resource service returns an empty object that is asynchronously filled after the requested data is obtained.

To solve this:

  1. Assign the requested data from a non $scope variable.
  2. Create a function callback in the query() action.
  3. Assign the non $scope variable in $scope.data within the function callback created in step 2.

e.g.

demo.controller('DemoController', ['$scope', '$state', '$stateParams', 'Demo', function($scope, $state, $stateParams, Demo) {   
    var queryData = Demo.query(function() {
      $scope.data = queryData;
    })
}]);

you may see other examples in here.

Autres conseils

Use ng-cloak on the parent element.

<div ng-cloak>
    :: all the bindings that you want to wait for the bind to hapen
</div>

AngularJS ng-cloak

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top