Javascript 如何等待ng repeat完成循环?
我有一个从服务器获取json并将其附加到列表的示例 脚本:Javascript 如何等待ng repeat完成循环?,javascript,angularjs,Javascript,Angularjs,我有一个从服务器获取json并将其附加到列表的示例 脚本: $http.get('/data/json/cities.json').then(function (res) { if (res.status === 200) { $scope.cities = res.data; } }); Html: json对象包含键NY,但我只能在1秒(或更长)后分配给对象(li带有idNY的标记) 有没有其他方法可以知道对象($('li#NY')在本例中)在没有使用set
$http.get('/data/json/cities.json').then(function (res) {
if (res.status === 200) {
$scope.cities = res.data;
}
});
Html:
json对象包含键NY
,但我只能在1秒(或更长)后分配给对象(li
带有idNY
的标记)
有没有其他方法可以知道对象(
$('li#NY')
在本例中)在没有使用setTimeout
的情况下成功创建的时间?您必须创建一个指令,请遵循下面的代码
var module = angular.module('app', [])
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit(attr.onFinishRender);
});
}
}
}
});
然后,在控制器中,您可以使用$on捕捉它:
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
//you also get the actual event object
//do stuff, execute functions -- whatever...
console.log($('li#NY').length); // 1
});
使用类似以下内容的html:
<li ng-repeat="(id, name) in cities" id="{{id}}" on-finish-render="ngRepeatFinished">
<a href="#" ng-bind="name"></a>
</li>
你到底想做什么?代码中不清楚您为什么需要此信息。请尝试使用ng repeat end
directive@Karim什么不清楚?该列表包含$('li#NY')
对象,该对象将在我获得json后创建。但是当我得到json时,我只能在1秒后分配给对象。@Hading repeat start
&ng repeat end
将有助于放置指令模板(多模板重复)的起点和终点。。我想OP需要答案。@PankajParkar谢谢你的链接。我刚刚又查过了。在指令内部,我必须至少等待1秒来检查长度。它可以工作。非常感谢。你能解释一下为什么我需要$timeout
在那里吗?$timeout确保它在ng重复元素真正完成渲染时执行(因为$timeout将在当前摘要周期结束时执行,并且它还将在内部调用$apply,与setTimeout不同)。因此,在ng重复完成后,我们使用$emit将事件发送到外部作用域(兄弟作用域和父作用域)。
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
//you also get the actual event object
//do stuff, execute functions -- whatever...
console.log($('li#NY').length); // 1
});
<li ng-repeat="(id, name) in cities" id="{{id}}" on-finish-render="ngRepeatFinished">
<a href="#" ng-bind="name"></a>
</li>