Angular - ui-router How to go to a specific part of the page

I know how to pass a variable reference to a Ui-router.

<a ui-sref="Category({ SCID: sc.scid })" ui-sref-active="active" >{{ sc.scname }}</a> 

and handle in routing.

 .state('Category', { templateUrl: "templates/Products.html", url: '/Category/:SCID/', controller: 'ProductsController as pc' }) 

Now I want to go to a specific part of this page. the section starts with id = 123.

 <section id="123"> reach here directly on clicking link</section> 

This question was also asked by another user. AngularJS ui.router change the page and go to a specific section

But this has no answer.

Can someone help me what change I need to make in the URL and .state.

+4
source share
2 answers

You are looking for $anchorScroll()

Basically, you need to set up routes as usual by passing a scroll parameter, for example:

 url: '/first/:scrollTo', 

and just add the following by typing $anchorScroll and it will scroll you to any item with the id found in $location.hash()

 app.run(function($rootScope, $location, $anchorScroll, $stateParams, $timeout) { $rootScope.$on('$stateChangeSuccess', function(newRoute, oldRoute) { $timeout(function() { $location.hash($stateParams.scrollTo); $anchorScroll() }, 100) }); }) 

Then in your html the links should look like this:

 <a href ui-sref="first({scrollTo: 'foo'})">First / Foo</a> 

Here is the plunker


Alternatively, you can create the onEnter: function in your state to do this:

 .state('first', { url: '/first/:scrollTo', controller: 'FirstCtrl', templateUrl: 'first.html', onEnter: function ($location, $stateParams, $anchorScroll, $timeout) { $timeout(function() { $location.hash($stateParams.scrollTo); $anchorScroll() }, 100) } }) 

Keeping things in a state:

 .state('first', { url: '/first/:scrollTo', controller: 'FirstCtrl', templateUrl: 'first.html', onEnter: scrollTo }) 


 var scrollTo = function() { function ($location, $stateParams, $anchorScroll, $timeout) { $timeout(function() { $location.hash($stateParams.scrollTo); $anchorScroll() }, 100) } }; 
+8
source

One option is to scroll to this section when you go to this particular page.

For this purpose you can use the angular-scroll directive.

You can find sectionId in the controller with $scope.sectionId = $stateParams['SCID'] || -1;//or some other default $scope.sectionId = $stateParams['SCID'] || -1;//or some other default , and then scroll to it:

 var scrollOffset = 0, duration = 400; var sectionElementId = "section" + $scope.sectionId; //you need to prefix the div id with "section" in this case or use just the SectionId var sectionElement = angular.element(document.getElementById(sectionElementId)); $document.scrollToElement(sectionElement, scrollOffset, duration); 
+1
source

All Articles