Page loading with $rootScope variable - variable n

2019-08-18 07:15发布

问题:

I'm setting $rootScope.pageLoading = 1 in the router config like this:

.state('app', {
      abstract: true,
      url: '',
      templateUrl: 'tpl/app.html',
      resolve: { 
         loading: function($rootScope){
             $rootScope.pageLoading = 1;
         }
     },
     controller: 'AppCtrl'
  })

And in the top level of the document, I have a spinner:

<!-- page loading -->
<div id="page-loading" ng-show="pageLoading">
    <small-spinner class="spinner fa-spin"></small-spinner>
</div>

When a page loads, I cancel the spinner inside the page's controller, like this:

angular
    .module('app')
    .controller('FilesController', FilesController);

    FilesController.$inject = ['$scope', 'Bolt', '$rootScope']

    function FilesController($scope, Bolt, $rootScope){

        activate();

        function activate() {
            var contenttype = 'files';
            var order = 'title';
            var limit = 500;
            var page = 1;

            return Bolt.getRecords(contenttype, order, limit, page)
                .then(function(data){
                    $rootScope.pageLoading = 0;
                });
        }
    }

This works fine only when the page is refreshed, i.e. it doesn't work on a simple state change, even though all states are child states of 'app'. What I was going for is that the $rootScope.pageLoading variable is reset whenever a change of state occurs. What am I doing wrong here?

回答1:

you should use $stateChangeStart

 $rootScope.$on("$stateChangeStart", function(event, next, current) {
            $rootScope.pageLoading = 1;
        });

Add this to your app controller. Now every time when your state changes, it will reset your pageLoading variable to 1.