I think I have identified some odd AngularJS1 behaviour concerning the timing of ng-repeat running and therefore conflicting with the timing of controller execution.
My controller automatically scrolls down to an html anchor ID: $anchorScroll('html_id');
This works fine with static html (static html plunker)
<div id="hello1">Hello1 </div>
But anchorScroll doesnt seem to work if it is called by the controller on divs generated by ng-repeat (ng-repeat plunker)
<div id="{{ITEM.slug}}" ng-repeat="ITEM in LIST">{{ITEM.slug}}</div>
NOTE:: anchorScroll on ng-repeat works fine with a button but I want it to scroll automatically ON LOADING...
(I have also tried usig ng-init= to call a scroll function, but same timing problem - so it cant find the anchor... even if coded AFTER the ng-repeat)
Any ideas / workarounds?
(there doesnt seem to be any ng-repeat events to bind to...)
For this to work, $anchorScroll
has to execute after the digest cycle, so that the items have actually been rendered.
The easiest way to make this happen is to use $timeout
with a 0
second delay, which creates a promise that will be resolved. With the 0
delay, the promise will be handled after the current digest cycle completes, instead of being handled immediately.
testApp.controller('testCtrl', function($scope, $anchorScroll, $timeout) {
$scope.LIST = [{
"slug": "hello1"
}, {
"slug": 'hello2'
}, {
"slug": 'hello3'
}];
$timeout(function() {
$anchorScroll('hello3');
}, 0);
});