如何在AngularJS表格加载完成前显示加载GIF动画
实现AngularJS表格加载前显示动画的方案
嘿,作为AngularJS新手遇到这个问题很正常,其实实现起来很简单,核心就是用一个状态变量来控制加载动画和表格的显示切换,我给你一步步讲怎么改:
第一步:在控制器中添加加载状态管理
我们需要在控制器里初始化一个加载状态变量,当数据请求完成后再把这个变量设为false,这样就能精准控制动画的显示时机。
修改你的app.js代码,添加状态变量并在请求完成后更新:
var app = angular.module('myApp', ['ui.bootstrap']); app.filter('startFrom', function() { return function(input, start) { if(input) { start = +start; //parse to int return input.slice(start); } return []; } }); app.controller('customersCrtl', function ($scope, $http, $timeout) { // 初始化加载状态:默认正在加载 $scope.isLoading = true; $http.get('ajax/getCustomers.php') .success(function(data){ $scope.list = data; $scope.currentPage = 1; //current page $scope.entryLimit = 5; //max no of items to display in a page $scope.filteredItems = $scope.list.length; //Initially for no filter $scope.totalItems = $scope.list.length; // 数据加载完成,关闭加载状态 $scope.isLoading = false; }) .error(function() { // 加载出错也要关闭加载状态,避免一直显示动画 $scope.isLoading = false; alert('数据加载失败,请稍后重试'); }); // 以下是你原有的其他方法,保持不变 $scope.setPage = function(pageNo) { $scope.currentPage = pageNo; }; $scope.filter = function() { $timeout(function() { $scope.filteredItems = $scope.filtered.length; }, 10); }; $scope.sort_by = function(predicate) { $scope.predicate = predicate; $scope.reverse = !$scope.reverse; }; });
第二步:在HTML模板中控制动画和表格的显示
接下来在你的页面里,用ng-show(或ng-if)指令根据isLoading变量来切换加载动画和表格的显示:
<!-- 加载动画:仅当isLoading为true时显示 --> <div ng-show="isLoading" style="text-align: center; padding: 30px 0;"> <img src="你的加载GIF路径" alt="正在加载..." style="width: 50px; height: 50px;" /> <p>正在加载数据,请稍候...</p> </div> <!-- 表格:仅当isLoading为false时显示 --> <table ng-show="!isLoading" class="table table-striped"> <thead> <tr> <!-- 这里是你的表头,比如: --> <th ng-click="sort_by('name')">姓名 <span class="glyphicon sort-icon" ng-show="predicate === 'name'" ng-class="{'glyphicon-chevron-up':reverse, 'glyphicon-chevron-down':!reverse}"></span> </th> <th ng-click="sort_by('email')">邮箱</th> <!-- 其他表头字段 --> </tr> </thead> <tbody> <tr ng-repeat="item in list | startFrom:(currentPage-1)*entryLimit | filter:search | orderBy:predicate:reverse"> <td>{{item.name}}</td> <td>{{item.email}}</td> <!-- 其他表格内容 --> </tr> </tbody> </table>
额外小提示
- 记得把代码里的
你的加载GIF路径替换成你实际的GIF文件路径哦 - 如果你想彻底移除未加载完成的表格DOM,可以用
ng-if="!isLoading"代替ng-show="!isLoading",两者的区别是ng-if会动态添加/移除DOM,而ng-show只是通过CSS隐藏 - 另外,AngularJS的
success和error方法已经被弃用了,推荐换成更标准的then和catch写法,比如:
$http.get('ajax/getCustomers.php') .then(function(response) { var data = response.data; $scope.list = data; // 其他数据初始化操作... $scope.isLoading = false; }) .catch(function(error) { $scope.isLoading = false; console.error('加载出错:', error); });
内容的提问来源于stack exchange,提问作者rohit nair
相关产品推荐
相关产品推荐

