javascript 在 AngularJS 中加载时隐藏模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18943967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hide template while loading in AngularJS
提问by Kirill Ryabin
What is the better solution to hide template while loading data from server?
从服务器加载数据时隐藏模板的更好解决方案是什么?
My solution is using $scope
with boolean variable isLoadingand using directive ng-hide
, ex: <div ng-hide='isLoading'></div>
我的解决方案是使用$scope
布尔变量isLoading和 using 指令ng-hide
,例如:<div ng-hide='isLoading'></div>
Does angular has another way to make it?
angular 是否还有其他方法可以实现?
回答by Harshad
You can try an use the ngCloak directive.
您可以尝试使用 ngCloak 指令。
Checkout this link http://docs.angularjs.org/api/ng.directive:ngCloak
回答by Rafal Pastuszak
The way you do it is perfectly fine (I prefer using state='loading' and keep things a little bit more flexible.)
你这样做的方式非常好(我更喜欢使用 state='loading' 并让事情变得更加灵活。)
Another way of approaching this problem are promises and $routeProvider resolve
property.
Using it delays controller execution until a set of specified promises is resolved, eg. data loaded via resource services is ready and correct. Tabs in Gmail work in a similar way, ie. you're not redirected to a new view unless data has been fetched from the server successfully. In case of errors, you stay in the same view or are redirected to an error page, notthe view, you were trying to load and failed.
解决这个问题的另一种方法是承诺和$routeProvider resolve
财产。使用它会延迟控制器执行,直到解决一组指定的承诺,例如。通过资源服务加载的数据已准备就绪且正确。Gmail 中的标签以类似的方式工作,即。除非成功从服务器获取数据,否则您不会重定向到新视图。如果出现错误,您会停留在同一个视图中或被重定向到错误页面,而不是视图,您尝试加载并失败。
You could configure routes like this:
您可以像这样配置路由:
angular.module('app', [])
.config([
'$routeProvider',
function($routeProvider){
$routeProvider.when('/test',{
templateUrl: 'partials/test.html'
controller: TestCtrl,
resolve: TestCtrl.resolve
})
}
])
And your controller like this:
你的控制器是这样的:
TestCtrl = function ($scope, data) {
$scope.data = data; // returned from resolve
}
TestCtrl.resolve = {
data: function ($q, DataService){
var d = $q.defer();
var onOK = function(res){
d.resolve(res);
};
var onError = function(res){
d.reject()
};
DataService.query(onOK, onError);
return d.promise;
}
}
Links:
链接:
回答by Amaury D
That's how I do:
这就是我的做法:
$scope.dodgson= DodgsonSvc.get();
In the html:
在 html 中:
<div x-ng-show="dodgson.$resolved">We've got Dodgson here: {{dodgson}}. Nice hat</div>
<div x-ng-show="dodgson.$resolved">We've got Dodgson here: {{dodgson}}. Nice hat</div>
<div x-ng-hide="dodgson.$resolved">Latina music (loading)</div>
<div x-ng-hide="dodgson.$resolved">Latina music (loading)</div>