LoginSignup
80
79

More than 5 years have passed since last update.

ビューのレンダリングが始まる前に特定の処理を完了させたいとき

Last updated at Posted at 2014-01-19

やり方はいろいろあると思います

ひとつは、$routeProviderのresolveを使う方法

あるURLに飛ぶ前に、必ず現在のユーザの情報をhttpで取ってきて$scopeに入れたい。
入れ終わってからビューを描画したいという状況だとします

index.html
<h2>demo</h2>
<div ng-app="app">
    <script type="text/ng-template" id="sample.html">
        <p>sample</p>           
        {{user}}
    </script>
    <div ng-view></div>
</div>

app.js
angular.module('app', ['ngRoute']).
config(function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: 'sample.html',
        controller: function($scope, currentUser){
            $scope.user = currentUser;
        },
        resolve: {
            currentUser: function($q, $http) {
                deferred = $q.defer()
                $http(url: '/yourappapi/v1/current_user', method: 'GET')
                .success(function(res){
                    deferred.resolve(res.user)
                });
                return deferred.promise;
            }
        }
    });
});

routeProviderのresolveオプションはcontrollerにinjectionされるオブジェクトのmapです
オブジェクトはpromiseを指定することになっており、このpromiseが解決したタイミングで
controllerにinjectionされます。
このため、API経由でユーザ情報を無事に取ってこれた後にcontroller内のコードが走ります。

実際には、良く使う初期化処理である場合は
resolveの処理をserviceに追い出してやった方が見通し良いでしょう

current_user_service.js
angular.module('app').factory('getCurrentUser', function($q, $http) {
    deferred = $q.defer();
    $http(url: '/yourappapi/v1/current_user', method: 'GET')
    .success(function(res) {
        deferred.resolve(res.user);
    });
    return deferred.promise;
});
$routeProvider.when('/', {
    templateUrl: 'sample.html',
    controller: function($scope, currentUser){
        $scope.user = currentUser;
    },
    resolve: {
        currentUser: function(getCurrentUser) { return getCurrentUser; }
    }
});


test

80
79
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
80
79