我正在编写一个 AngularJS 应用程序,但我对它很陌生,所以在下面的代码中,请指出您遇到的任何问题。
我的 AngularJS 应用程序确实有这样的定义:
var OfficeUIModule = angular.module('OfficeUI', ['ngSanitize']);
然后,我有几个服务可以从各种 JSON 文件加载数据。 但我不会在这里发布代码,因为我确实认为这无关紧要。
然后我就有了我的 Controller ,它基本上是这样的:
OfficeUIModule.controller('OfficeUIController', function($scope) { });
现在,我希望 Controller 在启动时执行一些逻辑并在其上显示一个 DIV 元素。 这是我想做的事情:
- 在初始设置期间显示
Loading
DIV 元素。 - 在初始化完成后显示一个
Displaying
DIV 元素。
假设在我的 Controller 中我有初始化应用程序的方法:
OfficeUIModule.controller('OfficeUIController', function($scope) {
function Init() {
// I'll load all the data from the services here.
}
});
为了在启动时调用这个方法,我只是在我的 Controller 中这样定义它:
OfficeUIModule.controller('OfficeUIController', function($scope) {
Init();
function Init() {
// I'll load all the data from the services here.
}
});
我想使用的 HTML 如下:
<body>
<div id="loading">LOADING</div>
<div id="displaying">DISPLAYING</div>
</body>
最初加载页面时,我想显示“正在加载”元素。 加载页面后,我想显示“正在显示”元素。
为了使其可测试,我更改了 Controller 方法 Init
以包含 5 秒的超时,如下所示:
OfficeUIModule.controller('OfficeUIController', function($scope) {
Init();
function Init() {
setTimeout(function() {
alert('Page has been loaded. When you click OK the displaying DIV should be showed.');
}, 5000);
}
});
因此,在这种特殊情况下,我想确保页面正在加载,显示 LOADING div,并在 5 秒后显示 DISPLAYING div。
我也不想看到任何闪烁,因此可以使用我读过的 ng-cloak,但我无法正确配置它。
这是我已经尝试过的:
加载中 展示中
但是,该设置效果不佳。
我添加了一个 Plunker以便您可以测试您提供的解决方案。
最佳答案
发生这种情况是因为您正在使用带有匿名函数的 setTimeout
并且 angularjs 不知道模型更改
http://plnkr.co/edit/FJ2lnrmtG7P3HXZuxRkH?p=preview
如果你使用 angularjs $timeout
就可以了
$timeout(function() {
$scope.initialized = true;
}, 5000);
您还可以使用 $scope.$digest()
或 $scope.$apply
使其工作
关于javascript - 隐藏元素直到加载完成(ng-cloak 不是我需要的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29343501/