Angularjs: how to scroll a page after showing ng-show hidden elements?

I have a list of hidden items. I need to show a list and then scroll to one of them with one click. I reproduced the code here: http://plnkr.co/edit/kp5dJZFYU3tZS6DiQUKz?p=preview

As I see on the console, scrollTop () is called before the elements are visible, so I think ng-show is not instantaneous, and this approach is incorrect. It works to delay scrollTop () with a timeout, but I don't want to do this.

Are there other solutions?

+8
angularjs asynchronous scroll ng-show
source share
2 answers

I see no other solution than to defer the call to scrollTop() when using ng-show . You need to wait until the changes in your model are reflected in the DOM, so the elements become visible. The reason that they do not appear instantly is the life cycle of the sphere. ng-show internally uses a clock listener that runs only when the $digest() function of the area is called after the full code has been executed in the click handler.

See http://docs.angularjs.org/api/ng.$rootScope.Scope for a more detailed explanation of the area's life cycle.

Normally, you should not use a timeout that runs after this event without delay:

 setTimeout(function() { $(window).scrollTop(50); }, 0); 

Alternative solution without timeout:

However, if you want to avoid a timeout event (the execution of which may precede other events in the event queue) and make sure that scrolling occurs inside the click event handler. In the controller, you can do the following:

 $scope.$watch('itemsVisible', function(newValue, oldValue) { if (newValue === true && oldValue === false) { $scope.$evalAsync(function() { $(window).scrollTop(50); }); } }); 

The listener starts with the same $digest() call as the clock listener registered with the ng-show directive. The function passed to $evalAsync() is executed angular immediately after processing all the watch handlers, so the elements were already visible with the ng-show directive.

+15
source share

You can use $anchorScroll .
Here is the documentation:

https://docs.angularjs.org/api/ng/service/$anchorScroll

Example:

 $scope.showDiv = function() { $scope.showDivWithObjects = true; $location.hash('div-id-here'); $anchorScroll(); } 
0
source share

All Articles