这是我的Demo
app.run(function($rootScope, $location, $anchorScroll) {
//when the route is changed scroll to the proper element.
$rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
console.log("called routeChangeSuccess");
if ($location.hash()) $anchorScroll();
});
});
我做错了什么?或者这与角度有关吗?
注意:黑客为此将使用点击事件,这应该工作我正在寻找直接的解决方案
使用角度和路线版本1.5.5
*添加了Bounty
答案 0 :(得分:2)
我检查了你的plunkr,我注意到你没有指定路线,当给出锚标签,因此' $ routeChangeSuccess'当我将特定行更改为此
时,不会触发<a href="/one/#one"> go to end of one </a>
我的主题滚动工作正常。
解决方案: Plunkr
请注意HTML5模式在路由here中遇到的挑战,如果您尚未考虑这一点。
答案 1 :(得分:1)
您基本上需要触发anchorscroll()
上的locationchange
。为此,您无需检查$routeChangeSuccess
。您可以直接使用$locationChangeStart
$rootScope.$on('$locationChangeStart', function(event) {
$anchorScroll();
});
要同时使用$routeChangeSuccess
或$locationChangeStart
,您需要为anchor
标记指定路由名,如下所示
<a href="/one/#one"> go to end of one </a>
更新了Plunkr
答案 2 :(得分:0)
试试这个:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.js"></script>
<base href="/"/>
</head>
<body ng-app="myApp">
<a ng-click="goTo('#one')" > go to end of one </a>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<div id="one">
This is one.
</div>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.run(function($rootScope, $location, $anchorScroll) {
//when the route is changed scroll to the proper element.
// $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
// console.log("called routeChangeSuccess");
// if ($location.hash()) $anchorScroll();
// });
$rootScope.goTo = function(value){
$location.hash(value);
};
});
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "/one.html"
})
.when("/one", {
templateUrl: "/one.html"
});
$locationProvider.html5Mode(true).hashPrefix('!');
});
</script>
</body>
</html>
希望这有帮助。