Search code examples
angularjsionic-frameworkhybrid-mobile-app

how to implement Draggable element in ionic v1


Hi Guys My requirement is to make an element draggable across the screen and set the position of the element to the place where users stops dragging. So far I am able to make a element draggable across the screen but once released it is going back to its old position (position where it was earlier) I am using ngDraggable directive of angular. Sorry I am new to Ionic and angular. Any help will be highly appreciated. My code goes as follows

<div ng-drag="true" id="draggableAxis" ng-style="{{draggedStyle}}" ng-drag-success="onDragComplete($data,$event)">
            <img src="img/axis.png" >
            <img ng-src="img/other.png" style="width:75px"> 
        </div> 

In my controller:

$scope.draggedStyle = {top: '96px',
    right: '90px'};
    var onDraggableEvent = function(evt, data) {           
      if(evt.name=='draggable:start'){
        console.log('draggable-start');
        console.log(data.x);
        console.log(data.y);
      }else{
        console.log('draggable-end');
        console.log(data);
        console.log(data.element.centerX +'  '+data.element.centerY);
        console.log(evt);
        $scope.setPosition(data);
        
    } 
}
    $scope.onDragComplete=function(data,evt){
       console.log("drag success, data:", data);
       console.log(evt);
    }// this fn doesnot gets triggered
    $scope.$on('draggable:start', onDraggableEvent);    
    $scope.$on('draggable:end', onDraggableEvent);
     
    $scope.setPosition=function(data){
        $scope.draggedStyle = {
            top: data.x+'px',
            right:  data.y+'px'
        };
     }

SCREEN SHOT OF MOBILE VIEW


Solution

  • I updated the fix to https://plnkr.co/edit/fVaIUVvAd7jLETkwVepm?p=preview

    One of the problems was

    ng-style="{{draggedStyle}}" 
    

    which should be

    ng-style="draggedStyle" 
    

    Also, I switched the setPosition method to flip the x and y and used left because x indicates position from the left and not right.

    $scope.setPosition = function(data) {
        $scope.draggedStyle = {
          top: data.y + 'px',
          left: data.x + 'px'
        };
      }
    

    Hope that helps