Organiccat
Organiccat

Reputation: 5651

Basic draggable with AngularJS?

I don't want draggable sortable elements or anything fancy, just a draggable element, like a normal jQuery div draggable object:

$("#draggable").draggable();

What is the proper way to do this through Angular? Do I still use jQueryUI, or is there anything in AngularUI I can use? I looked through both Angular libraries but didn't find anything specifically addressing draggable objects.

Upvotes: 24

Views: 25582

Answers (1)

Andrew Joslin
Andrew Joslin

Reputation: 43023

Use a directive.

Example:

angular.module("myApp").directive('andyDraggable', function() {
  return {
    restrict: 'A',
    link: function(scope, elm, attrs) {
      var options = scope.$eval(attrs.andyDraggable); //allow options to be passed in
      elm.draggable(options);
    }
  };
});

HTML

<div andy-draggable>Drag me!</div>
<div andy-draggable="{key: value}">Drag me with options!</div>

Documentation on directives: http://docs.angularjs.org/guide/directive

You could also create data-binding for the element's current position during the drag, hook up events, etc. But this is a really basic version.

Upvotes: 39

Related Questions