我有以下 ngRepeat 元素的 HTML:
<ol id="animationFrame">
<li ng-repeat="animationImage in animationImages" ng-repeat-listener>
<img ng-src="{{animationImage.src}}" id="{{animationImage.id}}">
</li>
</ol>
我想在其中使用angular.element
基于id
进行选择,如下所示:
angular.element('#animation-image-' + Math.floor($scope.animation.frameImage));
其中 $scope.animation.frameImage
向下舍入为整数。我可以看到我使用了正确的选择器(例如,'#animation-image-1'
是最初加载的选择器),并且当我更改 $scope.animation.frameImage
使用 slider ,效果完美。
问题是当页面加载时,使用正确的选择器返回的angular.element
对象是未定义
。现在,我认为这是因为 ng-repeat 尚未填充。因此,我为上面的 HTML 中包含的 ng-repeat-listener
添加了以下指令:
.directive('ngRepeatListener', function() {
return function(scope) {
if(scope.$last) {
scope.$emit('NGREPEATCOMPLETE');
}
}
我这样使用它:
$scope.$on('NGREPEATCOMPLETE', function() {
console.log(angular.element('#animation-image-1'));
};
它实际上在某个时刻被调用(谁知道它是否在正确的时间)。
为什么这不起作用?我该如何修复它?
最佳答案
ngRepeat 在渲染阶段之前不会渲染。要通过 angular.element() 访问元素,您可以使用 $evalAsync:
$scope.$evalAsync(function() { angular.element(...);});
$timeout 也可以工作,但它会在 $timeout 之后触发摘要。如果您希望在渲染后访问准备就绪的 DOM,并且不想在之后触发另一个摘要,请使用 $evalAsync。
[编辑]
正如 @maurycy 提到的,$timeout 有第二个参数以避免触发另一个摘要:
$timeout(function() {...}, 0, false);
关于javascript - 无法在 ng-repeat 内使用 angular.element 进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34679995/