document getElementById在重复的dom元素中返回null

document getElementById returns null in ng-repeated dom elements

本文关键字:元素 返回 null dom getElementById document      更新时间:2023-09-26

我有一个ng-repeat循环与画布项目:

<ul>
    <li ng-repeat="item in todos">
        <canvas id="canvas-{{item.Guid}}"></canvas>
    </li>
</ul>

在代码的某个地方,有一个addTodo函数,它有点像:

            $scope.todos.push(newTodo); 
            $scope.renderPDF(newTodo.Attachment,cxId);

其中cxId是画布id和renderPDF渲染画布上的东西使用getElementById。但是当我添加todo时,虽然在Chrome Developer Console中有具有正确id的画布,但我得到的错误是getElementById on cxId返回null。一切都做得很好,而且Angular使用了双向数据绑定,那么为什么会有问题呢?

我想解释一下,因为它很奇怪。Angular使用双向数据绑定,但在ng-book中我读到了这个过程。所有在视图中的参数(在本例中,也包括生成canvas-id的todos),所有在作用域中的参数都被设置为监视它们。在他们的变化中,有一个视图的变化。这个过程是双向数据绑定。它发生在消化循环中。所以有一个时间来做这个,当我把todo推到数组时,它还没有开始这个摘要循环。解决方案是在将元素添加到数组后强制摘要循环,它将侦听作用域变量的变化:

代替:

$scope.todos.push(newTodo);    
$scope.renderPDF(newTodo.Attachment,cxId);

应该有:

$scope.todos.push(newTodo);    
$scope.apply();
$scope.renderPDF(newTodo.Attachment,cxId);

apply方法强制摘要循环。