我正在制作一个看起来像这样的角度任务列表
可排序的列表标记
<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');
});
});
尽管目前这工作正常,但我无法摆脱完全错误的感觉......这会以某种方式破坏我的应用程序吗?它被认为是丑陋的黑客吗?