Reputation:
I've an example to get json from server and append it to a list.
Script:
$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>
The code where I'm stuck:
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);
}
The json object contains the key NY
but I can only assign to the object (li
tag with id NY
) after 1 second (or longer).
Is there another way to know when an object ($('li#NY')
in this case) has been created successful without using setTimeout
?
Upvotes: 1
Views: 384
Reputation: 980
You have to create a directive, follow code below.
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);
});
}
}
}
});
And then in your controller, you can catch it with $on:
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
//you also get the actual event object
//do stuff, execute functions -- whatever...
console.log($('li#NY').length); // 1
});
With html that looks something like this:
<li ng-repeat="(id, name) in cities" id="{{id}}" on-finish-render="ngRepeatFinished">
<a href="#" ng-bind="name"></a>
</li>
Upvotes: 1