Angularjs拖放表列

时间:2014-07-04 14:46:02

标签: angularjs angularjs-directive

您好我使用" asutosh"代码:

myApp.directive('droppable', ['$parse',
function($parse) {
return {

  link: function(scope, element, attr) {

    function onDragOver(e) {

      if (e.preventDefault) {
        e.preventDefault();
      }

      if (e.stopPropagation) {
        e.stopPropagation();
      }
      e.dataTransfer.dropEffect = 'move';
      return false;
    }

    function onDrop(e) {
      if (e.preventDefault) {
        e.preventDefault();
      }
      if (e.stopPropagation) {
        e.stopPropagation();
      }
      var data = e.dataTransfer.getData("Text");

      data = angular.fromJson(data);

      var dropfn = attr.drop;
      var fn = $parse(attr.drop);
      scope.$apply(function() {

        scope[dropfn](data, e.target);
      });

    }



    element.bind("dragover", onDragOver);
    element.bind("drop", onDrop);




  }
};


}
]);
myApp.directive('draggable', function() {

return {

link: function(scope, elem, attr) {

  elem.attr("draggable", true);
  var dragDataVal='';
  var draggedGhostImgElemId='';
  attr.$observe('dragdata',function(newVal){
    dragDataVal=newVal;

  });

  attr.$observe('dragimage',function(newVal){
    draggedGhostImgElemId=newVal;
  });

  elem.bind("dragstart", function(e) {
    var sendData = angular.toJson(dragDataVal);
    e.dataTransfer.setData("Text", sendData);
    if (attr.dragimage !== 'undefined') {
      e.dataTransfer.setDragImage(
        document.getElementById(draggedGhostImgElemId), 0, 0
      );

    }

    var dragFn = attr.drag;
    if (dragFn !== 'undefined') {
      scope.$apply(function() {
        scope[dragFn](sendData);
      })

    }

  });


}


 };


 });

示例http://plnkr.co/edit/KvJglc?p=preview,用于拖放表格列,但此代码有一点问题,当您将列放在标题中的边框或空白区域上时,列会消失。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

myApp.directive('angTable', ['$compile',function($compile) {
return {
  restrict: 'E',
  templateUrl: 'tabletemplate.html',
  replace: true,

  scope: {
    conf: "="

  },
  controller: function($scope) {

    $scope.dragHead = '';
    $scope.dragImageId = "dragtable";


    $scope.handleDrop = function(draggedData,
      targetElem) {

      var swapArrayElements = function(array_object, index_a, index_b) {
        var temp = array_object[index_a];
        array_object[index_a] = array_object[index_b];
        array_object[index_b] = temp;
      };

      var srcInd = $scope.conf.heads.indexOf(draggedData);
      var destInd = $scope.conf.heads.indexOf(targetElem.textContent);
      swapArrayElements($scope.conf.heads, srcInd, destInd);

    };

    $scope.handleDrag = function(columnName) {

      $scope.dragHead = columnName.replace(/["']/g, "");

    };



  },
  compile: function(elem) {
    return function(ielem, $scope) {

      $compile(ielem)($scope);


    };


  }
};


}

]);

if(destInd == -1) destInd = targetElem.cellIndex;之后添加这2行var destInd = $scope.conf.heads.indexOf(targetElem.textContent);,它应该可以正常工作