私はこれを少し違った方法で行いました。ディレクティブのコントローラー内に jquery ui 要素をアタッチする代わりに、ディレクティブのリンク関数内でそれを行いました。Ben Farrellのブログ投稿に基づいて、解決策を思いつきました。
これはRails
アプリであり、acts_as_list
gem を使用してポジショニングを計算していることに注意してください。
app.directive('sortable', function() {
return {
restrict: 'A',
link: function(scope, elt, attrs) {
// the card that will be moved
scope.movedCard = {};
return elt.sortable({
connectWith: ".deck",
revert: true,
items: '.card',
stop: function(evt, ui) {
return scope.$apply(function() {
// the deck the card is being moved to
// deck-id is an element attribute I defined
scope.movedCard.toDeck = parseInt(ui.item[0].parentElement.attributes['deck-id'].value);
// the id of the card being moved
// the card id is an attribute I definied
scope.movedCard.id = parseInt(ui.item[0].attributes['card-id'].value);
// edge case that handles a card being added to the end of the list
if (ui.item[0].nextElementSibling !== null) {
scope.movedCard.pos = parseInt(ui.item[0].nextElementSibling.attributes['card-pos'].value - 1);
} else {
// the card is being added to the very end of the list
scope.movedCard.pos = parseInt(ui.item[0].previousElementSibling.attributes['card-pos'].value + 1);
}
// broadcast to child scopes the movedCard event
return scope.$broadcast('movedCardEvent', scope.movedCard);
});
}
});
}
};
});
重要なポイント
- カードの属性を使用して、カードの ID、デッキ、および位置を保存し、
jQuery sortable
ウィジェットが取得できるようにします。
stop
イベントが呼び出された後、すぐにscope.$apply
関数を実行して、Misko Hevery が呼び出したangular execution context
.
- 私のGitHub Repoに、これを実際に動かしている例があります。