我有以下Angular和HTML来显示和重新加载图像列表:
<script type="text/javascript">
var application = angular.module('Application', []);
application.service('ImageService', function ($http) {
return {
GetList: function (page) {
return $http.get('api/images', { params: { page: page } });
},
}
});
application.controller('ImageController', function ImageController($scope, ImageService) {
var page = 0;
$scope.images = [];
var load = function () {
ImageService.GetList(page)
.success(function (data, status, headers, config) {
$scope.images = $scope.images.concat(data);
})
.error(function (data, status, headers, config) { });
}
$scope.reload = function () {
page++;
load();
}
load();
});
</script>
<div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in images' class="image">
<img src="{{image.Url}}" alt="" />
</div>
<a href="" class="reload" data-ng-click="reload()">load more</a>
</div>
如何更改&#34;加载更多&#34;的文本?做&#34;加载......&#34;并在加载时停用按钮?
答案 0 :(得分:3)
你可以创建一个'loading'指令,当有待处理的$ http请求时禁用按钮/链接:
<强>指令强>
app.directive('loading', function($http) {
return {
restrict: 'A',
scope: true,
link: function(scope, element) {
scope.pending = $http.pendingRequests;
scope.$watch('pending.length', function (length) {
if (length > 0)
{
element.attr('disabled', 'disabled');
}
else {
element.removeAttr('disabled');
}
});
}
}
});
<强>控制器强>
app.controller('ctrl', function($scope, $http) {
$scope.load = function() {
$http({url: 'api/get', method:'GET'}).success(function(data) {
$scope.data = data;
});
}
});
<强> HTML 强>
<div ng-controller="ctrl">
<button ng-click="load()" loading>Click Me</button>
</div>
答案 1 :(得分:2)
您可以将其绑定到范围:
<script type="text/javascript">
var application = angular.module('Application', []);
application.service('ImageService', function ($http) {
return {
GetList: function (page) {
return $http.get('api/images', { params: { page: page } });
},
}
});
application.controller('ImageController', function ImageController($scope, ImageService) {
var page = 0;
$scope.images = [];
$scope.loading = false;
$scope.loadingText = function() {
if ($scope.loading) {
return 'loading';
}
return 'load more';
}
var load = function () {
$scope.loading = true;
ImageService.GetList(page)
.success(function (data, status, headers, config) {
$scope.images = $scope.images.concat(data);
})
.error(function (data, status, headers, config) { })
.finally(function() {$scope.loading = false});
}
$scope.reload = function () {
page++;
load();
}
load();
});
</script>
<div data-ng-app="Application" data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in images' class="image">
<img src="{{image.Url}}" alt="" />
</div>
<a ng-disabled="{{loading}}" href="" class="reload" data-ng-click="reload()">{{loadingText()}}</a>
</div>