Angular语言 - ui-router如何转到页面的特定部分



我知道如何将变量传递给Ui-router中的链接。

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

并在路由中处理。

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

现在我想去那个页面的特定部分。假设section以id=123开头。

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

这个问题也有其他用户在这里问过。AngularJS ui。路由器更改页面,进入特定的章节

但是没有任何答案。

谁能帮我什么改变我需要在URL和。state.

您要找的是$anchorScroll()

基本上,你需要做的就是像往常一样设置你的路由,传递滚动参数:
url: '/first/:scrollTo',  

并添加以下内容,注入$anchorScroll,它将滚动到具有$location.hash()

id的任何元素
app.run(function($rootScope, $location, $anchorScroll, $stateParams, $timeout) { 
  $rootScope.$on('$stateChangeSuccess', function(newRoute, oldRoute) {
    $timeout(function() { 
      $location.hash($stateParams.scrollTo);
      $anchorScroll()
    }, 100)
  });
})
然后,在你的html中,链接应该看起来像:
<a href ui-sref="first({scrollTo: 'foo'})">First / Foo</a>

这是一个活塞


或者,您可以在您的状态中创建一个onEnter:函数来管理它:

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

让事情变得更简单:

.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)
  }
};

一个选项是当你到达那个特定的页面时滚动到那个部分。

你可以使用angular-scroll指令。

你可以用$scope.sectionId = $stateParams['SCID'] || -1;//or some other default在控制器中找到sectionId,然后滚动到它:

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);

最新更新