I know how to pass variable to a link in Ui-router.
<a ui-sref="Category({ SCID: sc.scid })" ui-sref-active="active" >{{ sc.scname }}</a>
and handle then in routing.
.state('Category', {
templateUrl: "templates/Products.html",
url: '/Category/:SCID/',
controller: 'ProductsController as pc'
})
Now i want to go to specific portion of that page. say section starts with id=123.
<section id="123"> reach here directly on clicking link</section>
This question has been asked here by some other user also. AngularJS ui.router change page and go to specific section
But that don't have any answer.
Can somebody help me what change i need to make in URL and .state.
You are looking for $anchorScroll()
Basically, what you need to do is to set your routes as usual, passing the scroll param like:
url: '/first/:scrollTo',
and just add the following, injecting $anchorScroll
and it will scroll you to any element 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:
<a href ui-sref="first({scrollTo: 'foo'})">First / Foo</a>
Alternatively, you can create an onEnter:
function in your state to mange 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 simpler in the 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)
}
};
One option would be to scroll to that section when you get to that specific page.
You can use the angular-scroll directive for that purpose.
You can find the sectionId in the controller with $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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With