I am new to Angular and am trying to create a directive that will attach a position to an element to the model - after the user drags it. I found another question that solves this for a simple object:
binding Angularjs attribute of left and top position after drag and drop
myApp.directive('draggable', function () { return { restrict: 'A', link: function (scope, element, attrs) { element.draggable({ cursor: "move", stop: function (event, ui) { scope[attrs.xpos] = ui.position.left; scope[attrs.ypos] = ui.position.top; scope.$apply(); } }); } }; });
See here the Fiddle solution: http://jsfiddle.net/mrajcok/5Mzda/
Now I am trying to get this to work with a more complex object and with ng-repeat , but cannot understand why it is not working.
Here is my HTML:
<div ng-controller="MyCtrl"> <div ng-repeat="position in positions"> <input type="number" ng-model="position.divleft"/> <input type="number" ng-model="position.divtop"/> <p draggable class="example" ng-style="{left: position.divleft, top: position.divtop}" xpos="position.divleft" ypos="position.divtop">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </div> </div>
And here is the JS:
var myApp = angular.module('myApp', []); function MyCtrl($scope) { $scope.positions = [ {"divtop": 80, "divleft": 200 }, {"divtop": 100, "divleft": 250 } ]; }; myApp.directive('draggable', function () { return { restrict: 'A', link: function (scope, element, attrs) { element.draggable({ cursor: "move", stop: function (event, ui) { scope[attrs.xpos] = ui.position.left; scope[attrs.ypos] = ui.position.top; scope.$apply(); } }); } }; });
Here is the scenario:
http://jsfiddle.net/5Mzda/19/
I don't seem to see what is wrong with the code. Would thank for any help!
UPDATE
I read the comments in more detail in the original question, and it looks like using $eval works:
myApp.directive('draggable', function () { return { restrict: 'A', link: function (scope, element, attrs) { element.draggable({ cursor: "move", stop: function (event, ui) { scope.$eval(attrs.xpos + '=' + ui.position.left); scope.$eval(attrs.ypos + '=' + ui.position.top); scope.$apply(); } }); } }; });
Not sure if there is a more elegant way to do this, but the binding seems to work correctly!