11'use strict' ;
2+ /*
3+ jQuery UI Sortable plugin wrapper
4+
5+ @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
6+ */
27angular . module ( 'ui.sortable' , [ ] ) . value ( 'uiSortableConfig' , { } ) . directive ( 'uiSortable' , [
38 'uiSortableConfig' ,
49 '$log' ,
@@ -34,37 +39,47 @@ angular.module('ui.sortable', []).value('uiSortableConfig', {}).directive('uiSor
3439 element . sortable ( 'refresh' ) ;
3540 } ;
3641 callbacks . start = function ( e , ui ) {
42+ // Save position of dragged item
3743 ui . item . sortable = { index : ui . item . index ( ) } ;
3844 } ;
3945 callbacks . update = function ( e , ui ) {
46+ // For some reason the reference to ngModel in stop() is wrong
4047 ui . item . sortable . resort = ngModel ;
4148 } ;
4249 callbacks . receive = function ( e , ui ) {
4350 ui . item . sortable . relocate = true ;
51+ // if the item still exists (it has not been cancelled)
4452 if ( 'moved' in ui . item . sortable ) {
53+ // added item to array into correct position and set up flag
4554 ngModel . $modelValue . splice ( ui . item . index ( ) , 0 , ui . item . sortable . moved ) ;
4655 }
4756 } ;
4857 callbacks . remove = function ( e , ui ) {
58+ // copy data into item
4959 if ( ngModel . $modelValue . length === 1 ) {
5060 ui . item . sortable . moved = ngModel . $modelValue . splice ( 0 , 1 ) [ 0 ] ;
5161 } else {
5262 ui . item . sortable . moved = ngModel . $modelValue . splice ( ui . item . sortable . index , 1 ) [ 0 ] ;
5363 }
5464 } ;
5565 callbacks . stop = function ( e , ui ) {
66+ // digest all prepared changes
5667 if ( ui . item . sortable . resort && ! ui . item . sortable . relocate ) {
68+ // Fetch saved and current position of dropped element
5769 var end , start ;
5870 start = ui . item . sortable . index ;
5971 end = ui . item . index ( ) ;
72+ // Reorder array and apply change to scope
6073 ui . item . sortable . resort . $modelValue . splice ( end , 0 , ui . item . sortable . resort . $modelValue . splice ( start , 1 ) [ 0 ] ) ;
6174 }
6275 } ;
6376 scope . $watch ( attrs . uiSortable , function ( newVal ) {
6477 angular . forEach ( newVal , function ( value , key ) {
6578 if ( callbacks [ key ] ) {
79+ // wrap the callback
6680 value = combineCallbacks ( callbacks [ key ] , value ) ;
6781 if ( key === 'stop' ) {
82+ // call apply after stop
6883 value = combineCallbacks ( value , apply ) ;
6984 }
7085 }
@@ -74,10 +89,12 @@ angular.module('ui.sortable', []).value('uiSortableConfig', {}).directive('uiSor
7489 angular . forEach ( callbacks , function ( value , key ) {
7590 opts [ key ] = combineCallbacks ( value , opts [ key ] ) ;
7691 } ) ;
92+ // call apply after stop
7793 opts . stop = combineCallbacks ( opts . stop , apply ) ;
7894 } else {
7995 log . info ( 'ui.sortable: ngModel not provided!' , element ) ;
8096 }
97+ // Create sortable
8198 element . sortable ( opts ) ;
8299 }
83100 } ;
0 commit comments