[英]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? 参数完成加载后如何加载模板?
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): 但是
ui.router
支持这种情况(和ngRoute
)和一个状态的resolve
参数,你可以延迟加载一个视图,直到所有的promise都被解析(或者其中一个被拒绝):
$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: 然后,可以将
dashboard
(与其他服务一样)注入mainDashboardApi
控制器:
app.controller('mainDashboardApi', ['$scope', 'dashboard',
function($scope, dashboard) {
$scope.dashboard = dashboard;
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.