我做的有点不同。我没有在指令的控制器中附加一个 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 存储库中,我有一个实际的工作示例。