I have a simple Angularjs app with a controller containing a scope list of strings called id
:
angular.module('app', [])
.controller('appCtrl', ['$scope', '$timeout',
function($scope, $timeout) {
$scope.ids = ['id1', 'id2'];
}]);
In the html partial an ngrepeat iterates over ids and add this ids to a list of divs:
<div ng-app="app">
<div ng-controller="appCtrl">
<div ng-repeat="id in ids" ng-attr-id="{{id}}">
div-{{id}}
</div>
</div>
</div>
These divs can be selected with angular.element in the controller only when it is included in a $timeout:
$timeout(function(){
console.log('with timeout, element found');
console.log(angular.element('#'+$scope.ids[0]));
});
console.log('no timeout, element not found');
console.log(angular.element('#'+$scope.ids[0]));
Here is a working example: https://codepen.io/neptune01/pen/zjqGzO
What exactly causes this asynchronous flow? Why do I need timeout to select the elements?
I'm trying to get rid of timeouts where possible. Is there a better way to do this element selection, without timeout eventually?