如何处理AngularJS锚散列连接 [英] How to handle anchor hash linking in AngularJS

查看:131
本文介绍了如何处理AngularJS锚散列连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做任何你知道如何很好地处理了锚散列连接AngularJS?

Do any of you know how to nicely handle anchor hash linking in AngularJS?

我有一个简单的FAQ页面下面的标记

I have the following markup for a simple FAQ-page

<a href="#faq-1">Question 1</a>
<a href="#faq-2">Question 2</a>
<a href="#faq-3">Question 3</a>

<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="fa1-3">Question 3</h3>

当点击上述任何环节AngularJS拦截和路线我到一个完全不同的页面(在我的情况下,404页,因为没有匹配的链接路径。)

When clicking on any of the above links AngularJS intercepts and routes me to a completely different page (in my case, a 404-page as there are no routes matching the links.)

我首先想到的是要建立一个路由匹配:一个匹配的元素之后/ FAQ /章,并在相应的控制器检查$ routeParams.chapter然后使用jQuery向下滚动到它。
不过话又说回来AngularJS对我妈的,只是滚动到页面顶部反正。

My first thought was to create a route matching "/faq/:chapter" and in the corresponding controller check $routeParams.chapter after a matching element and then use jQuery to scroll down to it. But then AngularJS shits on me again and just scrolls to the top of the page anyway.

所以,任何人都在这里完成过类似的事情,知道一个好的解决方案呢?

So, anyone here done anything similar in the past and knows a good solution to it?

编辑:切换到html5Mode要解决我的问题,但我们还挺有支持IE8 +反正让我担心它不是一个接受的解决方案:/

Switching to html5Mode should solve my problems but we kinda have to support IE8+ anyway so I fear it's not an accepted solution :/

推荐答案

您正在寻找 $ anchorScroll()

这里的(糟糕的)文档。

而这里的来源。

基本上你只注入并调用它在你的控制器,它会滚动你的ID在 $的location.hash()

Basically you just inject it and call it in your controller, and it will scroll you to any element with the id found in $location.hash()

app.controller('TestCtrl', function($scope, $location, $anchorScroll) {
   $scope.scrollTo = function(id) {
      $location.hash(id);
      $anchorScroll();
   }
});

<a ng-click="scrollTo('foo')">Foo</a>

<div id="foo">Here you are</div>

这里是展示一个plunker

Here is a plunker to demonstrate

编辑:与路由使用

设置您的角度路由像往常一样,然后只需添加以下code。

Set up your angular routing as usual, then just add the following code.

app.run(function($rootScope, $location, $anchorScroll, $routeParams) {
  //when the route is changed scroll to the proper element.
  $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
    $location.hash($routeParams.scrollTo);
    $anchorScroll();  
  });
});

和你的链接应该是这样的:

and your link would look like this:

<a href="#/test?scrollTo=foo">Test/Foo</a>

下面是 Plunker证明具有路由滚动和$ anchorScroll

甚至简单:

app.run(function($rootScope, $location, $anchorScroll) {
  //when the route is changed scroll to the proper element.
  $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
    if($location.hash()) $anchorScroll();  
  });
});

和你的链接应该是这样的:

and your link would look like this:

<a href="#/test#foo">Test/Foo</a>

这篇关于如何处理AngularJS锚散列连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆