[AngularJS] Promises in config. 2. config().when()

Before we see how promise works in contrller. But in contrller it is not a good way to put promises.

When you route the page, before the controller get excuted and templated loaded, you can use 'resolve' keyword in config or service or factory.

Here we show how to use promise in config.

'resolve' get loaded before controller and template, good to load $http stuff.

            resolve: {
//appXXX is the ng-app appXXX:
function($q, $timeout){ //inject two services, function can inject services!!! var defer = $q.defer(); $timeout(function(){defer.resolve()}, 2000); return defer.promise // it is important to return the defer.promises .then(console.log("logout 1")) .then(console.log("logout 2")); } },

 

var app = angular.module("app", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
        .when('/',
        {
            resolve: {
                doFirst: function($q, $timeout){
                    var defer = $q.defer();
                    $timeout(function(){defer.resolve()}, 2000);
                    return defer.promise
                        .then(console.log("logout 1"))
                            .then(console.log("logout 2"));
                }
            },
            templateUrl: "app.html",
            controller: "AppCtrl"
        })
});
app.controller('AppCtrl',function($scope){
    $scope.model = {message: "It is great!"}
});

 

posted @ 2014-08-26 01:56  Zhentiw  阅读(232)  评论(0)    收藏  举报