Angular JS: 我们可以在没有定义路由的控制器上设置 resolve 或 promise 吗?
Angular JS: can we set resolve or promise on controller which did not have route defined?
我正在尝试在控制器渲染之前从服务器获取一些数据。
关于routeProvider
我已经找到了很多答案。
但是我的主要问题是我的控制器没有绑定任何路由。
那么有什么方法可以做到这一点吗?
我有以下方式的控制器...
<!-- HERE I WANT TO BLOCK RENDERING TILL DATA GET LOAD -->
<AppController>
<ng-view>
</AppController>
听起来 resolve
是您要查找的内容,但如果您没有为该控制器使用路由 table,则不会有此选项。为什么不在控制器中解决异步调用,并在回调中设置范围变量。这就是我对等待控制器 "rendering" 的期望的解释,而通过路由 table 的 resolve
将等待控制器 实例化 。观察以下...
module.controller('ctrl', function($scope, $http) {
$http.get('/uri').then(function(response) {
// set $scope variables here
});
console.log('executed first');
});
如果您的数据调用时间过长,您还可以设置一个变量来阻止相关视图呈现。这将防止 UI 从 "dancing." 观察对上述示例的以下更改...
<div ng-controller="ctrl" ng-show="resolved"></div>
module.controller('ctrl', function($scope, $http) {
$http.get('/uri').then(function(response) {
$scope.resolved = true; // show rendering
});
});
JSFiddle Link - 简化演示
JSFiddle Link - 演示 ng-if
一个想法行得通
在 html 控制器中:
<p ng-if="notLoadedContent">Wait</p>
<div ng-if="!notLoadedContent">Content fetched</div>
并且在 Controller 中,所有控制器都在一个函数内,将全部启动,并且控制器将是:
fetch(init)
$scope.notLoaded = true;
function init(){
$scope.notLoaded=false;
}
希望对你有帮助
我正在尝试在控制器渲染之前从服务器获取一些数据。
关于routeProvider
我已经找到了很多答案。
但是我的主要问题是我的控制器没有绑定任何路由。
那么有什么方法可以做到这一点吗?
我有以下方式的控制器...
<!-- HERE I WANT TO BLOCK RENDERING TILL DATA GET LOAD -->
<AppController>
<ng-view>
</AppController>
听起来 resolve
是您要查找的内容,但如果您没有为该控制器使用路由 table,则不会有此选项。为什么不在控制器中解决异步调用,并在回调中设置范围变量。这就是我对等待控制器 "rendering" 的期望的解释,而通过路由 table 的 resolve
将等待控制器 实例化 。观察以下...
module.controller('ctrl', function($scope, $http) {
$http.get('/uri').then(function(response) {
// set $scope variables here
});
console.log('executed first');
});
如果您的数据调用时间过长,您还可以设置一个变量来阻止相关视图呈现。这将防止 UI 从 "dancing." 观察对上述示例的以下更改...
<div ng-controller="ctrl" ng-show="resolved"></div>
module.controller('ctrl', function($scope, $http) {
$http.get('/uri').then(function(response) {
$scope.resolved = true; // show rendering
});
});
JSFiddle Link - 简化演示
JSFiddle Link - 演示 ng-if
一个想法行得通 在 html 控制器中:
<p ng-if="notLoadedContent">Wait</p>
<div ng-if="!notLoadedContent">Content fetched</div>
并且在 Controller 中,所有控制器都在一个函数内,将全部启动,并且控制器将是:
fetch(init)
$scope.notLoaded = true;
function init(){
$scope.notLoaded=false;
}
希望对你有帮助