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

时间:2015-08-06 15:36:42

标签: javascript angularjs

我知道如何将变量传递给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'
})

现在我想转到该页面的特定部分。说节以id = 123开头。

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

其他一些用户也在这里提出了这个问题。 AngularJS ui.router change page and go to specific section

但是没有任何答案。

有人可以帮我解决我需要在URL和.state中做出哪些更改。

2 个答案:

答案 0 :(得分:8)

您正在寻找$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>

这是plunker

或者,您可以在州内创建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)
  }
};

答案 1 :(得分:1)

当您到达该特定页面时,一个选项是滚动到该部分。

您可以为此目的使用angular-scroll指令。

您可以使用import scala.xml._ import collection.mutable.HashMap val noDupFile="nodup_steam_out.txt" io.Source.fromFile(noDupFile).getLines().toStream.par.foreach(res => { //.... }) 在控制器中找到 sectionId ,然后滚动到它:

$scope.sectionId = $stateParams['SCID'] || -1;//or some other default