如何在控制器完成加载参数后以角度加载模板?

时间:2015-05-12 22:04:53

标签: javascript angularjs

我遇到的问题是模板的加载时间早于控制器中的参数,因此用户会看到空块。

控制器:

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

路由器:

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

如何在参数完成加载后加载模板?

1 个答案:

答案 0 :(得分:2)

There are a number of things you could do.

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

UICollectionViewCell

That would be the manual way.

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

resolve

Then, $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; })' } } }) could be injected (like you would other services) into dashboard controller:

mainDashboardApi