「Ruby on Rails Tutorial」のサンプルアプリをAngularJSとBootstrap3を使う形にして作成します。今回は、ユーザー一覧表示機能をAngularJSの機能を使ってページ化して表示するように変更します。
“Angular directives for Bootstrap”のページネーションのディレクティブを使ってユーザー一覧をページ化します。
http://angular-ui.github.io/bootstrap/#/pagination
http://getbootstrap.com/components/#pagination
1)AngularJSビューを修正
前回作成したユーザー一覧の上部と下部にページネーションを追加します。
$ vi app/assets/templates/users/index.html.erb
<div ng-controller="UsersIndexCtrl">
<h1 class="text-center">All users</h1>
<pagination total-items="totalitems"
ng-model="currentpage"
max-size="maxsize"
items-per-page="itemsperpage"
class="pagination-sm"
previous-text="Previous"
next-text="Next"
first-text="First"
last-text="Last"
boundary-links="true">
</pagination><br />
<ul ng-repeat="user in currentitems" class="users">
<li><img alt="{\{user.name}}" src="https://secure.gravatar.com/avatar/{\{hash(user.email)}}?s=52" />
<a href="/users/{\{user.id}}">{\{user.name}}</a>
</li>
</ul>
<pagination total-items="totalitems"
ng-model="currentpage"
max-size="maxsize"
items-per-page="itemsperpage"
class="pagination-sm"
previous-text="Previous"
next-text="Next"
first-text="First"
last-text="Last"
boundary-links="true"
rotate="false">
</pagination>
</div>
2)AngularJSコントローラを修正
ページネーションに必要な各種定数を定義します。
myModule.controller("UsersIndexCtrl", function($scope, userResource, flashService, $location, sessionResource, $q) {
$scope.maxsize = 5;
$scope.itemsperpage = 3;
$scope.currentpage = 1;
var start = 0;
var end = start + $scope.itemsperpage;
var qgetUser = function(deferred) {
:
}
var deferred = $q.defer();
deferred.promise.then(function (result) {
var user_info = result;
if (user_info.user.id > 0) {
userResource.index({}, function(response) {
$scope.users = response;
$scope.totalitems = $scope.users.length;
$scope.currentitems = $scope.users.slice(start,end);
$scope.$watch('currentpage', function() {
start = ($scope.currentpage - 1) * $scope.itemsperpage;
end = start + $scope.itemsperpage;
$scope.currentitems = $scope.users.slice(start,end);
},true);
});
} else {
$location.path("/signin");
}
},function (reason) {
console.log("qgetUser-Error");
})
qgetUser (deferred);
$scope.hash = function(email) {
return md5(email.toLowerCase());
};
});