2014-05-08 02:58

[AngularJS] 製作 jQuery UI Sortable directive

Html
  1. <div jq-sortable="selectedList"> 
  2.    <div ng-repeat="item in selectedList"> 
  3.        <img ng-src="{{item.src}}" /> 
  4.    </div> 
  5. </div> 


JavaScript
  1. app.directive('jqSortable', ['$parse', function($parse) { 
  2.    return function(scope, element, attrs) { 
  3.        /*解析並取得表達式*/ 
  4.        var expr = $parse(attrs['jqSortable']); 
  5.        var $oldChildren; 
  6.  
  7.        element.sortable({ 
  8.            opacity: 0.7, 
  9.            scroll: false, 
  10.            tolerance: "pointer", 
  11.            start: function() { 
  12.                /*紀錄移動前的 children 順序*/ 
  13.                $oldChildren = element.children('[ng-repeat]'); 
  14.            }, 
  15.            update: function(){ 
  16.                var newList = []; 
  17.                var oldList = expr(scope); 
  18.                var $children = element.children('[ng-repeat]'); 
  19.  
  20.                /*產生新順序的陣列*/ 
  21.                $oldChildren.each(function(i){ 
  22.                    var index = $children.index(this); 
  23.                    if(index == -1){ return; } 
  24.  
  25.                    newList[index] = oldList[i]; 
  26.                }); 
  27.  
  28.                /*將新順序的陣列寫回 scope 變數*/ 
  29.                expr.assign(scope, newList); 
  30.  
  31.                /*通知 scope 有異動發生*/ 
  32.                scope.$digest(); 
  33.            } 
  34.        }); 
  35.  
  36.        /*在 destroy 時解除 Sortable*/ 
  37.        scope.$on('$destroy', function(){ 
  38.            element.sortable('destroy'); 
  39.        }); 
  40.    }; 
  41. }]); 

0 回應: