【发布时间】:2015-12-27 08:50:27
【问题描述】:
我正在编写应用程序功能,在请求执行时设置加载 gif(出于学习目的)。我使用 AngularJS 1.4.5、“Controller as”语法和 John Papa 风格指南。 所以,我写了一个 interceptor 将当前请求的数量传递给服务:
(function () {
'use strict';
angular
.module('eventApp')
.factory('requestInterceptorService', requestInterceptorService);
requestInterceptorService.$inject = ['$q', 'loadingService'];
function requestInterceptorService($q, loadingService) {
var numLoadings = 0;
var requestInterceptorServiceFactory = {
request: request,
response: response,
responseError: responseError
};
return requestInterceptorServiceFactory;
function request(config) {
numLoadings++;
loadingService.setLoaderStatus(numLoadings);
return config || $q.when(config);
}
function response(response) {
numLoadings--;
loadingService.setLoaderStatus(numLoadings);
return response || $q.when(response);
}
function responseError(response) {
numLoadings--;
loadingService.setLoaderStatus(numLoadings);
return $q.reject(response);
}
}
})();
这是我的 loading.service,带有 isLoadgerEnabled 标志,指示我们是否需要显示加载图像:
(function () {
'use strict';
angular
.module('eventApp')
.factory('loadingService', loadingService);
function loadingService() {
var isLoaderEnabled = false;
var loadingServiceFactory = {
setLoaderStatus: setLoaderStatus,
getLoaderStatus: getLoaderStatus,
isLoaderEnabled: isLoaderEnabled
};
return loadingServiceFactory;
function setLoaderStatus(numberOfRequests) {
var status = false;
if (numberOfRequests === 0) {
status = false;
}
if (numberOfRequests !== 0) {
status = true;
}
isLoaderEnabled = status;
}
function getLoaderStatus() {
return isLoaderEnabled;
}
}
})();
以上代码对我有用。 在视图中,我有 div 加载图像和 ng-show 指令,它监听来自 index 控制器的标志:
<div id="loaderDiv">
<img src="client/assets/img/loader.gif" class="content-loader"
ng-show="index.isLoaderEnabled" />
</div>
.controller('indexController', indexController);
indexController.$inject = ['$location', 'authService', 'authModal', 'loadingService', '$scope'];
function indexController($location, authService, authModal, loadingService, $scope) {
var vm = this;
vm.isLoaderEnabled = loadingService.isLoaderEnabled;
//code with other functionality
$scope.$watch(function () {
return loadingService.isLoaderEnabled;
}, function (newValue) {
vm.isLoaderEnabled = newValue;
});
}
})();
我的问题:vm.isLoaderEnabled 没有使用服务更新(实际上 vm.isLoaderEnabled 总是错误的),我不确定问题出在哪里。 我想为此功能编写高效而优雅的解决方案,也许没有 $scope (如果可能的话)。 我已准备好提出问题、重构建议或更好的想法来绑定数据以查看。
【问题讨论】:
-
您可以在您的 vm 对象上公开
loadingService,然后在您的 html 中执行 ng-show="index.loadingService.isLoaderEnabled" -
@JoseM 遗憾的是,这并没有帮助。 isLoaderEnabled(在控制器中)仅初始化一次,仅此而已
标签: javascript angularjs data-binding angularjs-scope angularjs-digest