「Ruby on Rails Tutorial」のサンプルアプリをAngularJSとBootstrap3を使う形にして作成します。ユーザープロファイルページで、ログインユーザーが該当ユーザーに対してfollow/unfollow出来るようにします。
まず今回は、ログイン済みユーザーと該当ユーザーとのフォロー状況を確認し、”follow”または”unfollow”のボタンを切り替えて表示する機能を作成します。
1)ユーザー詳細ビュー修正
$ vi app/assets/templates/users/show.html.erb
<div class="col-xs-6 col-sm-8">
<div ng-show="!flg_follers && chkSignin() &&
chkSignin().user.id != user_info.user.id" class="row">
<div ng-show="flg_unfollow">
<a class="btn btn-large btn-primary" href="#"
ng-click="unfollow(user_info.user.id)">
Unfollow
</a>
</div>
<div ng-hide="flg_unfollow">
<a class="btn btn-large btn-primary" href="#"
ng-click="follow(user_info.user.id)">follow</a>
</div>
</div>
2)AngularJSスクリプト修正
①$resourceサービスを使ってサーバーからユーザー情報取得。
userResource.show({ id: $routeParams.id }, function(response) {
:
②上記①でユーザ情報取得後、フォロー状況をチェック。
$resouceサービスの$qサービスを使ってchkUnfollow()を同期実行。
userResource.show({ id: $routeParams.id }, function(res;ponse) {
$scope.user_info = response;
chkUnfollow();
});
③上記②のchkUnfollow()内でログイン済みユーザー情報をqgetUser()を実行して取得。$qサービスを使ってqgetUser()を実行し、ログイン済みユーザー情報を取得してからフォローチェックを行う。
$ vi app/assets/javascripts/mymodule.js.erb
myModule.controller("UsersShowCtrl", function($scope, $routeParams, userResource, flashService, $filter, micropostsResource, $q) {
var qgetUser = function(deferred) {
if (flashService.getUser()) {
var quser_info = flashService.getUser();
deferred.resolve(quser_info);
} else {
sessionResource.current_user({}, function(response) {
if (response.user.id) {
var quser_info = response;
} else {
var quser_info = { user: {id: 0} };
}
flashService.setUser(quser_info);
deferred.resolve(quser_info);
});
}
}
var chkUnfollow = function() {
$scope.flg_unfollow = false;
var deferred = $q.defer();
deferred.promise.then(function (result) {
var user_signin = result.user.id;
for (var i=0; i<=$scope.user_info.followers.length; i++) {
if ($scope.user_info.followers[i] && $scope.user_info.followers[i].id == user_signin) {
$scope.flg_unfollow = true;
}
}
},function (reason) {
console.log("user_signin-Error");
},function (reason) {
console.log("user_signin");
})
qgetUser(deferred);
};
userResource.show({ id: $routeParams.id }, function(response) {
$scope.user_info = response;
chkUnfollow();
:
});