Drag & Dropでリストをソートする
リストのアイテムをドラッグ&ドロップで並べ替えるのに、 AngularJSのng-sortableというライブラリを使ってみました。
環境
- Rails 4.2.4
- AngularJS 1.3
ng-sortableのソースを配置する
https://github.com/a5hik/ng-sortable からzipをダウンロードして解凍し、 distディレクトリ内の以下のファイルを、Railsアプリに配置します。
- ng-sortable.js → RAILS_ROOT/vendor/assets/javascripts/
- ng-sortable.css → RAILS_ROOT/vendor/assets/stylesheets/
application.js
//= require ng-sortable
を追記します。
//= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require angular //= require angular-resource //= require ng-sortable //= require_tree .
application.css
*= require ng-sortable
を追記します。
*= require ng-sortable *= require_tree . *= require_self
実装
view
<html ng-app="todoApp"> ... <div ng-controller="TodoListCtrl as todoList"> ... <div data-as-sortable="dragControlListeners" data-ng-model="todos"> <div class="todo-body" data-ng-repeat="todo in todos" data-as-sortable-item> <input type="text" ng-model="todo.text" ng-blur="Update($index);"> <span data-as-sortable-item-handle><i class="fa fa-bars"></i></span> </div> </div> </div> </html>
javascript
angular.moduleのDependencyに'as.sortable'を追加します。
var todoApp = angular.module('todoApp', ['ngResource', 'as.sortable']);
README.md
Latest release version 1.3.1 [Module name is modified from 'ui.sortable' to 'as.sortable' from versions 1.3.x, considering the conflict with the sortable module from bootstrap-ui.]
Version 1.3.xからモジュールの名前が 'ui.sortable' から 'as.sortable' に変更になったそうなので注意。
README.md
Features:
- Drag both Horizontally and Vertically. 横と縦の両方にドラッグできる.
- Drag and Drop items within a column. 欄の範囲内でドラッグ&ドロップできる.
- Drag and Drop items across columns. 欄をまたいでドラッグ&ドロップできる.
- Can do Ranking by Sorting and Change Status by Moving.
- Hooks provided to invoke API's after a particular action.
- Preventing/Allowing Drop Zone can be determined at run time.
- Enable/Disable Drag at run time.
- Drag Boundary can be defined. ドラッグの境界を定義できる.
- Clone an item and drop. アイテムのクローンをドロップする.
参考
ng-sortable - AngularJS Modules, Plugins and Directives
RailsでAngularJSを使ってTodoアプリを作成 - 9. AngularJS + Railsでソート可能(Sortable)なリストを作成する - Rails Webook