Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The problem I have encountered is that the template is loaded earlier than the parameters in the controller and so 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 finish loading?

like image 945
Roman Avatar asked Oct 31 '22 04:10

Roman


1 Answers

There are a number of things you could do.

You could hide the empty blocks, and only show them when the data has loaded:

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;
        });
    }
]);

That would be the manual way.

But ui.router supports this sort of scenario (as does ngRoute) with a resolve parameter of a state, where you could delay loading a view until all the promises are resolved (or one of the 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;
                      })'
          }
        }
    })

Then, dashboard could be injected (like you would other services) into mainDashboardApi controller:

app.controller('mainDashboardApi', ['$scope', 'dashboard',
    function($scope, dashboard) {
        $scope.dashboard = dashboard;
    }
]);
like image 199
New Dev Avatar answered Nov 12 '22 15:11

New Dev