我正在编写应用程序功能,在请求执行时设置加载 gif(出于学习目的)。我使用 AngularJS 1.4.5、“Controller as”语法和 John Papa 风格指南。所以,我写了一个拦截器,将当前请求的数量传递给服务:
(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;
        }
    }
})();
上面的代码对我有用。在视图中,我有加载图像和ng-show 指令的div ,它从索引控制器侦听标志:
<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 (如果可能的话)。我已经准备好提出问题、重构建议或更好的想法来绑定数据以查看。