gpt4 book ai didi

javascript - 如何等到 ng-repeat 完成循环?

转载 作者:行者123 更新时间:2023-11-30 15:17:58 25 4
gpt4 key购买 nike

我有一个从服务器获取 json 并将其附加到列表的示例。

脚本:

$http.get('/data/json/cities.json').then(function (res) {
if (res.status === 200) {
$scope.cities = res.data;
}
});

HTML:

<li ng-repeat="(id, name) in cities" id="{{id}}">
<a href="#" ng-bind="name"></a>
</li>

我卡住的代码:

if (res.status === 200) {
$scope.cities = res.data;

// from here
console.log($('li#NY').length); // 0

// waiting 1 second and try again
setTimeout(function () {
console.log($('li#NY').length); // 1
}, 1000);
}

json 对象包含 key NY 但我只能在 1 秒后分配给对象(li 标签,id NY)(或更长)。

是否有另一种方法可以在不使用 setTimeout 的情况下知道何时成功创建对象($('li#NY'))?

最佳答案

你必须创建一个指令,遵循下面的代码。

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);
});
}
}
}
});

然后在您的 Controller 中,您可以使用 $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>

关于javascript - 如何等到 ng-repeat 完成循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44206158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com