gpt4 book ai didi

javascript - angularjs 可拖动指令在内部显示值

转载 作者:行者123 更新时间:2023-11-30 11:31:11 25 4
gpt4 key购买 nike

在指令开发者指南中,我试图扭曲关于可拖动指令的示例之一,并让它也显示它的坐标。

但我的代码更改使指令不可拖动。最重要的变化是我在指令中添加了范围,如下所示。任何人都可以提供帮助吗?完整的源代码可以在下面的链接中找到。谢谢!

https://plnkr.co/edit/muegeHyOWC828IjI84Tt?p=preview

scope:{
startX: '=',
startY: '=',
x: '=',
y: '='
},

最佳答案

您没有将 Controller 变量传递给指令:

<span my-draggable  
startX="startX" startY="startY"
x="x" y="y" >
Drag Me({{x}},{{y}})
</span>

Demo Plunker 1


但是如果你还想更新计数器,我会改为绑定(bind)方法:

  .directive('myDraggable', ['$document','$timeout', function($document,$timeout) {
return {
scope:{
onChange: '&'
},

link: function(scope, element, attr) {

scope.x=0;
scope.y=0;
scope.startX=0;
scope.startY=0;

element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer'
});

element.on('mousedown', function(event) {
console.log('mousedown');
// Prevent default dragging of selected content
event.preventDefault();

$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});



function mousemove(event) {
scope.y = event.pageY - scope.startY;
scope.x = event.pageX - scope.startX;

element.css({
top: scope.y + 'px',
left: scope.x + 'px'
});

$timeout(function(){
scope.onChange({data:{x:scope.x, y:scope.y}});
});
}

function mouseup() {
console.log('mouseup');
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
}
};
}])

Controller

 $scope.onChange = function(data){
$scope.x=data.x;
$scope.y=data.y;
}

HTML

  <span my-draggable  on-change="onChange(data)" >Drag Me({{x}},{{y}})</span>

Demo Plunker 2

关于javascript - angularjs 可拖动指令在内部显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46143701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com