gpt4 book ai didi

javascript - 如何从我的指令中调用 Controller 方法?

转载 作者:行者123 更新时间:2023-11-28 18:39:10 24 4
gpt4 key购买 nike

如何从我的指令调用 Controller 方法onDrag()

Html/(SVG)

<g ng-controller="EntityController as vm" draggable> ... </g>

指令

app.directive('draggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;

element.on('mousedown', function(event) {
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});

function mousemove(event) {
y = event.pageY - startY;
x = event.pageX - startX;
element.attr("transform", "translate(" + x + "," + y + ")");
// I want to call the controllers onDrag() here
// possibly passing in values
}

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

Controller

app.controller("EntityController", function () {
var vm = this;

vm.onDrag = function () {
// do stuff
}
});

如果我没有正确执行此操作,我不介意改变我的方法,最好传递要在同一 g 元素上的另一个 html 标签中调用的方法,例如 on-drag="vm.onDrag()";

更新

根据建议我更改了代码:

<g ng-controller="EntityController as vm" on-drag="vm.drag()" draggable>

app.directive('draggable', ['$document', function ($document) {
return {
scope: {
onDrag: '&'
},
link: ...
}
}

vm.drag = function() {
alert("you dragged something!");
};

警报未触发

最佳答案

您应该将函数传递给您的指令,您可以这样做:

app.directive('draggable', ['$document', function($document) {
return {
scope: {
updateFn: '&'
},
link: function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;

element.on('mousedown', function(event) {
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});

function mousemove(event) {
y = event.pageY - startY;
x = event.pageX - startX;
element.attr("transform", "translate(" + x + "," + y + ")");
scope.updateFn(); // this fires the callback
}

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

然后您应该将所需的函数传递给您的指令,如下所示:

<g ng-controller="EntityController as vm" draggable update-fn="vm.onDrag()"> ... </g>

现在,在指令的链接函数中,您可以在希望执行 Controller 的 onDrag 函数的任何位置调用scope.updateFn()。您可以在这里找到有关这意味着什么的更多信息: https://thinkster.io/egghead/isolate-scope-am

关于javascript - 如何从我的指令中调用 Controller 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36423400/

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