Delaying AngularJS route change until model loaded to prevent flicker

后端 未结 13 2285
误落风尘
误落风尘 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:22

    Here's a minimal working example which works for Angular 1.0.2

    Template:

    
    
    

    JavaScript:

    function MyCtrl($scope, datasets) {    
        $scope.datasets = datasets;
    }
    
    MyCtrl.resolve = {
        datasets : function($q, $http) {
            var deferred = $q.defer();
    
            $http({method: 'GET', url: '/someUrl'})
                .success(function(data) {
                    deferred.resolve(data)
                })
                .error(function(data){
                    //actually you'd want deffered.reject(data) here
                    //but to show what would happen on success..
                    deferred.resolve("error value");
                });
    
            return deferred.promise;
        }
    };
    
    var myApp = angular.module('myApp', [], function($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: '/editor-tpl.html',
            controller: MyCtrl,
            resolve: MyCtrl.resolve
        });
    });​
    ​
    

    http://jsfiddle.net/dTJ9N/3/

    Streamlined version:

    Since $http() already returns a promise (aka deferred), we actually don't need to create our own. So we can simplify MyCtrl. resolve to:

    MyCtrl.resolve = {
        datasets : function($http) {
            return $http({
                method: 'GET', 
                url: 'http://fiddle.jshell.net/'
            });
        }
    };
    

    The result of $http() contains data, status, headers and config objects, so we need to change the body of MyCtrl to:

    $scope.datasets = datasets.data;
    

    http://jsfiddle.net/dTJ9N/5/

提交回复
热议问题