Отображение результатов с использованием угловых js + php, как показывать изображение загрузчика до загрузки данных, здесь мой код написан ниже,
Как сделать так, чтобы AngularJS показывал загрузочное изображение, пока данные не закончили загрузку?
App.js файл
var app = angular.module('myApp3', ['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) {
$http.get('http://www.testurl.com/index.php/site/getprofileLocations').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 20; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
});
$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;
};
});
И PHP-код здесь
<html ng-app="myApp3" ng-app lang="en">
<div ng-controller="customersCrtl">
<div class="content" >
<div class="row">
<div class="col-md-2">PageSize:
<select ng-model="entryLimit" class="form-control">
<option>5</option>
<option>10</option>
<option>20</option>
<option>50</option>
<option>100</option>
</select>
</div>
<div class="col-md-3">Filter:
<input type="text" ng-model="search" ng-change="filter()" placeholder="Filter" class="form-control" />
</div>
<div class="col-md-4">
<h5>Filtered {{ filtered.length }} Of {{ totalItems}} Total Locations</h5>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-12" ng-show="filteredItems > 0">
<table class="table table-striped table-bordered">
<thead>
<th>Id <a ng-click="sort_by('id');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Place Name <a ng-click="sort_by('name');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Category ID <a ng-click="sort_by('category_name');"><i class="glyphicon glyphicon-sort"></i></a></th>
</thead>
<tbody>
<tr ng-repeat="data in filtered = (list | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
<td>{{data.id}}</td>
<td>{{data.name}}</td>
<td>{{data.category_name}}</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12" ng-show="filteredItems == 0">
<div class="col-md-12">
<h4>No Locations found</h4>
</div>
</div>
<div class="col-md-12" ng-show="filteredItems > 0">
<div pagination="" page="currentPage" on-select-page="setPage(page)" boundary-links="true" total-items="filteredItems" items-per-page="entryLimit" class="pagination-small" previous-text="«" next-text="»"></div>
</div>
</div>
</div>
</div>
<script src="<?php echo Yii::app()->baseUrl; ?>/angular/js/angular.min.js"></script>
<script src="<?php echo Yii::app()->baseUrl; ?>/angular/js/ui-bootstrap-tpls-0.10.0.min.js"></script>
<script src="<?php echo Yii::app()->baseUrl; ?>/angular/app/app.js"></script>
</html>
6 ответов
Показать загрузчик и скрыть его после загрузки данных.
$scope.showLoader = true;
$http.get('http://www.testurl.com/index.php/site/getprofileLocations').success(function(data){
$scope.showLoader = false;
// rest of your code
});
РЕДАКТИРОВАТЬ: HTML-код из ответа Саида
<div ng-show="showLoader"><!-- so this div containing img will be dislpayed only when the showLoader is equal to true-->
<img src="source"> <!-- or any other spinner -->
</div>
Есть лучший способ, который запрещает показывать две иконки, например:
(ПЛОХОЙ СПОСОБ)
Когда angular манипулирует DOM, он может показать значок поиска, прежде чем скрыть значок загрузки. Вот почему плохо иметь два элемента.
<i class="fa fa-search" ng-hide="loadingData" ></i>
<i class="fa fa-circle-o-notch fa-spin" ng-show="loadingData"></i>
(ХОРОШИЙ СПОСОБ)
Этот способ предотвращает отображение загрузки и значка поиска, когда Angular скрывает и показывает элементы.
<i class="fa" ng-class="loadingData ? 'fa-circle-o-notch fa-spin' : 'fa-search' " ></i>
И сценарий будет примерно таким.
$scope.clickEventThatDoSomething = function () {
$scope.loadingData = true;
http.get('http://YourAPIUrl').then(function (data) {
$scope.loadingData = false;
$scope.data = data.data;
}).catch(function (err) {
$scope.loadingData = false;
})
}
Вы можете сделать одну вещь:
- По умолчанию скрывайте html-контент
- Покажите это, когда получите ответ
Любить:
<div class="content" ng-show="!showLoader">
.....
</div>
Таким образом, использование только этого загрузчика покажет, пока вы не получите свои данные с сервера.
Дополнение к ответу @ Venugopal. Чтобы отобразить это изображение загрузки в HTML
<div ng-show="showLoader"><!-- so this div containing img will be dislpayed only when the showLoader is equal to true-->
<img src="source"> <!-- or any other spinner -->
</div>
Всякий раз, когда мы используем HTTP-вызов в AngularJS, мы хотим показать загрузочное изображение по умолчанию. Итак, здесь мы собираемся достичь этого с помощью пользовательской директивы.
JS CODE
var app = angular.module('appMyCustomModule',[]);
app.directive('dirCustomLoader', ['$http', function ($http) {
return {
restrict: 'E',
template: '<div class="loading-icon"></div>',
link: function (scope, element, attrs) {
scope.isLoading = function () {
return $http.pendingRequests.length > 0;
};
scope.$watch(scope.isLoading, function (value) {
if (value)
element.removeClass('ng-hide');
else
element.addClass('ng-hide');
});
}
};
}]);
CSS:
.loading-icon {
background: url(static image url) no-repeat scroll center #fff;
display: inline-block;
font-size: 0;
height: 100%;
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 9999999999999999999 !important;
opacity: .5;
}
КОД HTML:
<dir-custom-loader class="ng-hide"></dir-custom-loader>
Вам нужно показать образ загрузчика перед вызовом ajax и удалить его после его завершения как в успешном, так и в обработчике ошибок.
Вы найдете множество загрузочных изображений онлайн, которые вы можете использовать для своего приложения.
JS CODE
//show the loader image in center of screen & prevent any user interactions
$scope.imLoading = true;
$http.get('http://www.testurl.com/index.php/site/getprofileLocations').then(
function(data){
//hide the loader image & process successful data.
$scope.imLoading = false;
}, function (errorData) {
//hide the loader image & show error message to user
$scope.imLoading = false;
});
CSS:
.im_loading{
display:none;
position:fixed;
top:50%;
left:50%;
margin:-35px 0px 0px -35px;
background:#fff url(../images/loader.gif) no-repeat center center;
width:70px;
height:70px;
z-index:9999;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
-moz-box-shadow:1px 1px 3px #000;
-webkit-box-shadow:1px 1px 3px #000;
box-shadow:1px 1px 3px #000;
opacity:0.7;
filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70);
}
КОД HTML:
<div class="im_loading" ng-show:"imLoading"></div>
Примечание. Ваш код обрабатывает только успешный вызов ajax, а не ошибочный вызов, что нехорошо, поскольку ваш код перестает отвечать, когда возвращается ошибка, поэтому вам также необходимо обрабатывать случай ошибки.
Похожие вопросы
Связанные вопросы
Новые вопросы
javascript
По вопросам программирования на ECMAScript (JavaScript / JS) и его различных диалектах / реализациях (кроме ActionScript). Включите все соответствующие теги в свой вопрос; например, [node.js], [jquery], [json] и т. д.