Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

javascript - Angular.js delaying controller initialization

I would like to delay the initialization of a controller until the necessary data has arrived from the server.

I found this solution for Angular 1.0.1: Delaying AngularJS route change until model loaded to prevent flicker, but couldn't get it working with Angular 1.1.0

Template

<script type="text/ng-template" id="/editor-tpl.html">
Editor Template {{datasets}}
</script>
    <div ng-view>
</div>

?

JavaScript

function MyCtrl($scope) {    
    $scope.datasets = "initial value";
}

MyCtrl.resolve = {
    datasets : function($q, $http, $location) {
        var deferred = $q.defer();

        //use setTimeout instead of $http.get to simulate waiting for reply from server
        setTimeout(function(){
            console.log("whatever");
            deferred.resolve("updated value");
        }, 2000);

        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/1/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since $http returns a promise, it's a performance hit to create your own deferred just to return the promise when the http data arrives. You should be able to do:

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

If you need to do some processing of the result, use .then, and your promise is chained in for free:

MyCtrl.resolve = {
    datasets: function ($http) {
        return $http({method: 'GET', url: '/someUrl'})
               .then (function (data) {
                   return frob (data);
               });
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...