在得到回复之前显示加载器

时间:2015-11-19 10:59:20

标签: javascript angularjs ajax

需要在收到回复之前显示加载程序图像
我使用下面的代码:

HTML:

<div ng-app="myApp" ng-controller="customersCtrl">
    <div class="table-responsive">
        <table class="table table-striped table-hover table-condensed">
            <tr>
                <th>Name</th>
                <th>City</th>
                <th>Country</th>
            </tr>
            <tr ng-repeat="x in cus_names">
                <td>{{x.Name}}</td>
                <td>{{x.City}}</td>
                <td>{{x.Country}}</td>
            </tr>
        </table>
    </div>
</div>

JS:

var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php").success(function (response) {
        $scope.cus_names = response.records;
    });
});

提前致谢

1 个答案:

答案 0 :(得分:0)

创建一个ready标记,并使用它来显示或不显示您的加载图像。

<div ng-app="myApp" ng-controller="customersCtrl">
    <div class="table-responsive">
        <table class="table table-striped table-hover table-condensed">
            <tr>
                <th>Name</th>
                <th>City</th>
                <th>Country</th>
            </tr>
            <div ng-if="!ready">
               <!-- Put loading image here -->
            </div>
            <div ng-if="ready">
               <tr ng-repeat="x in cus_names">
                   <td>{{x.Name}}</td>
                   <td>{{x.City}}</td>
                   <td>{{x.Country}}</td>
               </tr>
            </div>
        </table>
    </div>
</div>

JS

angular.module('myApp', []);

angular.module('myApp").controller('customersCtrl', 
    function customersCtrl ($scope, $http) {
        $scope.ready = false;
        $http.get("http://www.w3schools.com/angular/customers.php"
            ) .then (function (response) {
                $scope.cus_names = response.data.records;
                $scope.ready = true; 
            }) .catch (function (error) {
                throw error;
            });
    }
);

请注意,.success方法现已弃用,我们应该从现在开始使用.then。有关详细信息,请参阅AngularJS $http API Docs