Delaying AngularJS route change until model loaded to prevent flicker

后端 未结 13 2327
误落风尘
误落风尘 2020-11-22 02:28

I am wondering if there is a way (similar to Gmail) for AngularJS to delay showing a new route until after each model and its data has been fetched using it

13条回答
  •  误落风尘
    2020-11-22 03:29

    You can use $routeProvider resolve property to delay route change until data is loaded.

    angular.module('app', ['ngRoute']).
      config(['$routeProvider', function($routeProvider, EntitiesCtrlResolve, EntityCtrlResolve) {
        $routeProvider.
          when('/entities', {
            templateUrl: 'entities.html', 
            controller: 'EntitiesCtrl', 
            resolve: EntitiesCtrlResolve
          }).
          when('/entity/:entityId', {
            templateUrl: 'entity.html', 
            controller: 'EntityCtrl', 
            resolve: EntityCtrlResolve
          }).
          otherwise({redirectTo: '/entities'});
    }]);
    

    Notice that the resolve property is defined on route.

    EntitiesCtrlResolve and EntityCtrlResolve is constant objects defined in same file as EntitiesCtrl and EntityCtrl controllers.

    // EntitiesCtrl.js
    
    angular.module('app').constant('EntitiesCtrlResolve', {
      Entities: function(EntitiesService) {
        return EntitiesService.getAll();
      }
    });
    
    angular.module('app').controller('EntitiesCtrl', function(Entities) {
      $scope.entities = Entities;
    
      // some code..
    });
    
    // EntityCtrl.js
    
    angular.module('app').constant('EntityCtrlResolve', {
      Entity: function($route, EntitiesService) {
        return EntitiesService.getById($route.current.params.projectId);
      }
    });
    
    angular.module('app').controller('EntityCtrl', function(Entity) {
      $scope.entity = Entity;
    
      // some code..
    });
    

提交回复
热议问题