我正在制作一个看似像这样的角度的任务列表
可排序列表标记
<ol>
<li><form id="task_creation_form"></form></li>
<li ng-repeat="task in tasks">{{task.name}}</li>
</ol>
正如您所看到的,即使表单可以被拖动也会导致我的表单在我的控制器中的$scope.tasks
发生更改后定位到整个地方,因为该表单不属于列表
为了解决这个问题,我最终在我的控制器中使用了这个逻辑,每次创建新任务时都会触发该逻辑,但在它被添加到$scope.tasks
数组之前
$scope.$on('task_created', function(event, task){
// Why the timeout?
// When the task_created event is fired from the $scope, the tasks
// property changes and the DOM get's updated. Thats is cool, but part
// of the 'tasks' list, is the new task form that can also be reordered,
// Therefore we need to detach it from the DOM, let the scope do it's digest and
// reattach the form afterwards to it's proper position.
// We wrap the entire thing in a setTimeout handler, so the $apply does not get
// automatically called and we force it to happen before re-attaching the creation form
setTimeout(function(){
// Tell the directive to detach the creation form (if it exists) so
// it's position doesn't get messed up when the tasks array is applied
$scope.$emit('detachCreationForm');
$scope.tasks.splice(task.order - 1, 0,task);
$scope.$apply();
// Tasks are properly reordered. Tell the directive to reattach the creation form
$scope.$emit('reattachCreationForm');
});
});
即使此刻工作正常,我也无法摆脱某些事情完全错误的感觉......这会以某种方式打破我的应用吗?它被认为是一个丑陋的黑客?