在我的项目中,canvas元素显示了一个操纵杆。通过鼠标/触摸事件,画布将更新为看起来像用户正在移动操纵杆。这很好用。坐标保存在如下对象中:
scope.point = {
x: 0,
y: 0,
};
我已添加此HTML以向用户显示:
<span>X:{{point.x.toFixed(2)}} Y:{{point.y.toFixed(2)}}</span>
问题是,当scope.point.x和scope.point.y的值发生更改时(在鼠标/触摸事件处理程序中),它们不会在HTML中更新。唯一的解决方案似乎是添加:
scope.$apply()
//or
scope.$digest()
到渲染循环。这确实有效,但似乎不优雅(imho)并且性能明显下降,正如预期的那样。
还有其他解决方案吗?
提前致谢。
PS:虽然我不认为它是相关的,但作为参考,这是事件处理程序代码和渲染循环:
//handles mouse or touch movement on joystick
scope.mouseMove = function(evt) {
if (leftClick == 1) { //check if left mouse button down or touch
// get cursor or touch coordinates, saved in point object.
if (evt.type == 'touchstart' || evt.type == 'touchmove') {
scope.point.x = evt.targetTouches[0].pageX - joystick.offsetLeft;
scope.point.y = evt.targetTouches[0].pageY - joystick.offsetTop;
} else {
scope.point.x = evt.pageX - joystick.offsetLeft - 3;
scope.point.y = evt.pageY - joystick.offsetTop - 3;
};
//make coordinates relative to canvas center
scope.point = GeometrySrv.centerCoord(scope.point, joystick);
//if Directional Lock is ON, enforce
if (scope.lockMode != "fullAnalog") {
scope.point = GeometrySrv.forceDirectionLock(scope.point.x, scope.point.y, scope.lockMode);
};
// force coordinates into maxRadius
if (!GeometrySrv.isInsideCircle(scope.point.x, scope.point.y, maxRadius)) {
scope.point = GeometrySrv.forceIntoCircle(scope.point.x, scope.point.y, maxRadius);
};
//send coordinates back to server (websocket)
updateJoystick(scope.point, scope.lockMode);
};
};
function renderLoop() {
//erases previous joystick position
resetJoystick();
// erases previous vector
resetVector();
//change coordinates to canvas reference
scope.point = GeometrySrv.canvasCoord(scope.point, joystick);
DrawSrv.drawLineFromCenter(joystickctx, scope.point.x, scope.point.y);
if (scope.showVector) {
DrawSrv.drawLineFromCenter(vectorctx, scope.point.x * vector.width / joystick.width, scope.point.y * vector.width / joystick.width);
};
//redraw joystick position
DrawSrv.drawCircle(joystickctx, scope.point.x, scope.point.y, radius, maxRadiusBGColor);
//change back to relative coordinates
scope.point = GeometrySrv.centerCoord(scope.point, joystick);
//scope.$digest();
//call renderLoop every 15ms (60fps)
renderReq = requestAnimationFrame(renderLoop);
};
答案 0 :(得分:0)
我只想制作一个过滤器,这样你仍然可以绑定到该对象,但你的过滤器会以特定的方式显示该对象。
[your angular module].filter('toFixed', [function () {
return function (input) {
if (typeof input.toFixed == 'function')
return input.toFixed(2);
return input;
};
}]);
然后用HTML绑定它:
<span>X:{{point.x | toFixed}} Y:{{point.y | toFixed}}</span>
答案 1 :(得分:0)
$apply
在内部调用$rootScope.$digest
,因此请在本地范围内使用$diggest
以获得更好的性能。为了获得最佳性能,请放弃数据绑定并直接操作DOM。您可以使用自己的角directive执行此操作。
答案 2 :(得分:0)
阅读$applyAsync() - 它允许你排队$ digest()循环并大约每隔10ms对其进行一次限制。
也很聪明地知道Angular是否已经在$ digest()循环中,避免了在$ digest()完成之前你会调用$ apply()两次的烦人错误。