IsaiahPacheco
5/7/2013 - 8:53 PM

Sortable List in Angular with add and remove functions expands upon sortable demo at http://jsfiddle.net/dj_straycat/Q5FWt/3/

Sortable List in Angular with add and remove functions expands upon sortable demo at http://jsfiddle.net/dj_straycat/Q5FWt/3/

'use strict';

angular.module('myApp').
  controller('sortableListController', [
    '$scope',
    function($scope) {
    $scope.listOfObjects = ["Item 1","Item2", "Item3", "Item4"];

    var sortableEle;
    

    $scope.sortableArray = $scope.listOfObjects;

    //The newArray object changes contents of sortable array

    $scope.changeListContents = function (newArray){
      $scope.sortableArray = newArray;
    }

    //add and remove specific list item by name (listItem represents a String)
    //empty argument result in last list item being removed or empty item added to list
    
    $scope.add = function( listItem ) {
      $scope.sortableArray.push( listItem );
    }

    $scope.remove = function( ListItem ) {
      $scope.sortableArray.splice($scope.sortableArray.indexOf( listItem ), 1);
    }
      
    $scope.dragStart = function(e, ui) {
      ui.item.data('start', ui.item.index());
    }

    $scope.dragEnd = function(e, ui) {
      var start = ui.item.data('start'),
            end = ui.item.index();
          
      $scope.sortableArray.splice(end, 0, 
      $scope.sortableArray.splice(start, 1)[0]);
        
      $scope.$apply();
    }

    //<ul> id can replace #SortableList  

    sortableEle = $('#SortableList').sortable({
        start: $scope.dragStart,
        update: $scope.dragEnd
    });
  }
])