How to load a template in angular after the controller finishes loading the parameters?

The problem that I encountered is that the template loads earlier than the parameters in the controller, and therefore the user sees empty blocks.

Controller:

app.controller('mainDashboardApi', ['$scope', '$http',
    function($scope, $http) {
        $http.get('api/dashboard/main').success(function(data) {
            $scope.dashboard = data;
        });
    }
]);

Router:

$stateProvider
    .state('dashboard', {
        url: "/dashboard",
        templateUrl: "dashboard",
        controller: 'mainDashboardApi'
    })

How can I make the template load after the parameters have finished loading?

+4
source share
1 answer

There are a few things you could do.

You can hide empty blocks and show them only when loading data:

app.controller('mainDashboardApi', ['$scope', '$http',
    function($scope, $http) {
        $scope.isLoading = true;

        $http.get('api/dashboard/main').success(function(data) {
            $scope.dashboard = data;
            $scope.isLoading = false;
        });
    }
]);

It will be a manual way.

But it ui.routersupports such a scenario (as well ngRoute) with a resolvestate parameter , where you can defer loading the view until all promises are resolved (or one of them is rejected):

$stateProvider
    .state('dashboard', {
        url: "/dashboard",
        templateUrl: "dashboard",
        controller: 'mainDashboardApi',
        resolve: {
          dashboard: function($http){
             return $http.get('api/dashboard/main')
                      .then(function(response){
                         return response.data;
                      })'
          }
        }
    })

dashboard (, ) mainDashboardApi:

app.controller('mainDashboardApi', ['$scope', 'dashboard',
    function($scope, dashboard) {
        $scope.dashboard = dashboard;
    }
]);
+2

All Articles