1. 程式人生 > >Angular框架中當前頁面跳轉

Angular框架中當前頁面跳轉

我們在使用 $routeProvider後,想在當前頁面中跳轉連線,往往得不到正確的跳轉。

例如:
test.html


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

由於 我們可能設定了 $routeProvider
app.js

var app = angular.module('angularjs-starter', []);

app.config(function($routeProvider) { 
  $routeProvider.when('/test', {
    controller: 'TestCtrl',
    templateUrl: 'test.html'
  })
  .when('/weee', {
    controller: 'WeeeCtrl',
    templateUrl: 'weee.html'
}) .otherwise({ redirectTo: '/test' }); });

為解決這個頁面內跳轉,有很多種解決辦法:

1、利用 ng-click 替換原來的 href,並新增相應的Controllerx響應

2、利用 $location.hash()

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(); }); });
<a href="#/test#foo">Test/Foo</a>

但是會重新整理的整個頁面

3、在a標籤中新增 target=”_self”

<a href="#faq-1" target="_self">Question 1</a>

這個方法簡單有效!

具體方法可以參考: