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>

这个方法简单有效!

具体方法可以参考:

http://stackoverflow.com/questions/14712223/how-to-handle-anchor-hash-linking-in-angularjs

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值