Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ui-router change state on scroll

Here is an example layout. Assuming that section height is more or equal user's viewport.

+----------+
| Section1 |
+----------+
| Section2 |
+----------+
| Section3 |
+----------+

All these sections are placed in one view. And I want to change browser url dynamically upon user scrolls page and reaches one of sections: At first time user see http://example.com/#/section1 (angular not using html5 mode), then he scrolls down a page and should see http://example.com/#/section2 when section2 element become visible at user's viewport. Also if user copies link, when he open i.e. http://example.com/#/section2 I need to scroll page to that section.

To detect which section is currently is been viewed by user I use angular-inview directive.

Now I've done it through parameter:

$state.go($state.current, {
    section: $scope.activeSectionId // e.g. 'section2'
}, {
    notify: false, // do not reload page
    location: 'replace' // do not save as new history entry
});

But this way isn't quiet good and url are not looking friendly. Also it has a bug, when I click on a link with ui-sref, for the first time page jumps, changes inview section for some time and triggers code mentioned above, so actually it not navigates according to ui-sref. But next time I click - all works well (this happens just after page reloading).

Can someone suggest how to do this better, if it actually possible?

like image 757
m03geek Avatar asked Dec 03 '14 16:12

m03geek


1 Answers

Why do you want to change state, when you $state.go($state.current)? Maybe use anchorScroll instead, not sure about html5.

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

EDIT:

Sorry, I missed about mouse scroll. Check this answer https://stackoverflow.com/a/14717011/1603188 and usage of $location.hash(id);

like image 99
Terafor Avatar answered Oct 18 '22 11:10

Terafor