Я нашел ответ MarCal невероятно полезно, и даже расширил его немного после обновления к моей БД, чтобы обновить значение последовательности каждого (контакты в пределах организации, в моем случае) в списке:
HTML (container is the contact.контакт, в моем случае, не может перемещаться между организациями):
<div class="container" [dragula]="'org-' + org.id" [dragulaModel]="org.contacts">
<nested-contact *ngFor="let contact of org.contacts" [user]="contact" class="contact" [attr.data-id]="contact.id"></nested-contact>
</div>
JS (в моих Контактах службе, функция PUT для обновления сохраненных значений последовательности, связанные с каждым из моих контактов, так что их заказы сохраняются):
contactsIdPut (id, body) {
let url = '/api/v3/contacts/' + id + '?access_token=' + localStorage.getItem('access_token');
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.put(url, body, options)
.map((response: Response) => {
return response.json();
});
}
JS (на мой взгляд, организация компонента, наметить меры, которые должны быть приняты при перетаскивании, соответственно):
export class nestedOrganizationComponent {
orgs = [];
thisOrg: any;
thisContact: any;
constructor (private _contactService: ContactService, private dragulaService: DragulaService) {
this._contactService = _contactService;
let dragIndex: any;
let dropIndex: any;
let elementNode: any;
dragulaService.drag.subscribe((value) => {
let id = Number(value[1].dataset.id);
let orgId: Number = value[0].split('-')[1];
elementNode = value[2].querySelectorAll('.contact:not(.ignore)').item(dragIndex);
if (!!id) {
// this renderedOrgs is just an array to hold the org options that render in this particular view
this._organizationService.renderedOrgs.push(this.org);
this.thisOrg = this._organizationService.renderedOrgs.filter(org => { return org.id == orgId; })[0];
this.thisContact = this.thisOrg.contacts.filter(contact => { return contact.id == id; })[0];
let arr = this.thisOrg.contacts.map(x => { return x.id; });
dragIndex = arr.indexOf(id);
}
});
dragulaService.drop.subscribe((value: any[]) => {
if (elementNode) {
let id = Number(elementNode.dataset.id);
if (!!id) {
let arr = this.thisOrg.contacts.map(x => { return x.id; });
dropIndex = arr.indexOf(id);
}
}
if (value[2] === value[3]) { // target container === source container
if (dragIndex >= 0 && dropIndex >= 0 && dragIndex !== dropIndex) {
this.thisOrg.contacts.forEach((contact, index) => {
contact.sequence = index;
this.updateSequence(contact.id, index);
});
}
}
});
}
updateSequence (id: Number, index: Number) {
let contactBody = {
avatar: {
sequence: index,
}
};
return this._contactService.contactsIdPut(id, contactBody)
.subscribe(
(data: any) => {
// nothing is needed, the same view can apply because the contact has already been moved.
},
(error: any) => {
console.error(error);
}
);
}
}
Надеюсь, это даст немного больше ясности по этому вопросу кому-то еще в месте, подобном тому, где я нашел себя сегодня.
Имея тот же вопрос и не могу найти ответ. Я фактически теряю элемент DOM, который я перетаскиваю, когда я его бросаю. Просто удаление '[dragulaModel] = 'myList'' похоже исправить это странное поведение (все еще способное перетаскивать), но больше не может вызвать вызов dragulaService.dropModel). –
@DanJ, я вижу только сценарий установки, ничего о onDrop или модели, возвращенной из onDrop? –
Извините, должно быть, была проблема с копией - кругом, пытаясь разобраться в проблеме. –