admin管理员组文章数量:1390248
I'm writing a directive for jqueryui draggable, but I'm having some trouble getting the left and top position to bind to my scope after dragging. Could someone point me in the right direction?
myApp.directive('draggable', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.draggable({
cursor: "move",
stop: function (event, ui) {
attrs.$set('xpos', ui.position.left);
}
});
}
};
});
Here's a fiddle of what I'm trying to do: /
I'm writing a directive for jqueryui draggable, but I'm having some trouble getting the left and top position to bind to my scope after dragging. Could someone point me in the right direction?
myApp.directive('draggable', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.draggable({
cursor: "move",
stop: function (event, ui) {
attrs.$set('xpos', ui.position.left);
}
});
}
};
});
Here's a fiddle of what I'm trying to do: http://jsfiddle/psinke/TmQeL/
Share Improve this question asked Jan 8, 2013 at 14:19 Peter SinkePeter Sinke 3071 gold badge3 silver badges7 bronze badges2 Answers
Reset to default 5Add to your directive:
scope: { xpos: '=', ypos: '=' },
The '=' syntax sets up two-way databinding between your isolate scope and the parent scope. Any changes you make to these isolate scope properties in your directive also affect the parent scope too, and vice versa.
Then in the linking function:
stop: function (event, ui) {
scope.xpos = ui.position.left;
scope.ypos = ui.position.top;
scope.$apply();
scope.$apply();
}
There is a currently a bug in Angular where you have to call $apply() twice if you're setting an attribute on an isolate scope property bound with =. See https://github./angular/angular.js/issues/1276
Update: @Peter noted in the ments that the above breaks moving the draggable via the input textboxes. I was unable to get it to work with an isolate scope, so I just had the directive use the parent scope (i.e., the directive does not create a new scope). I used attrs to modify the specified scope attribute in the stop() method. This works with multiple draggables on the same page.
stop: function (event, ui) {
scope[attrs.xpos] = ui.position.left;
scope[attrs.ypos] = ui.position.top;
scope.$apply();
}
Fiddle.
It is a mon problem faced by beginners.
Add the following code. it will work.
stop: function (event, ui) { scope.divleft = ui.position.left; scope.divtop = ui.position.top; scope.$apply(); }
Reason: Whenever change happens in the jquery world, it should be municated to AngularJS world by calling $scope.$apply().
版权声明:本文标题:javascript - Angularjs directive attribute binding of left and top position after dragging - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744658617a2618108.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论