我编写了一个应用程序,其中包含一系列块。
每个块都包含指向其他块的链接。当点击指向块的链接时,例如# /home/page-19,页面根据当前位置向下/向上动画。
这一切目前都可以正常工作,但当单击锚点并更新路由时,浏览器会跳转到顶部,然后再执行动画向下,我需要它从当前位置开始执行动画。
我编写了一个指令,将preventDefault添加到所有锚点。
请参见以下JS Fiddle。 http://jsfiddle.net/ygNWF/10/。
简化代码:
HTML:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<body ng-app="app" ng-controller="appController">
<script type="text/ng-template" id="home-template"></script>
<div class="wrapper">
<div class="view" ng-view scroll></div>
</div>
</body>
javascript:
var app = angular.module('app', []);
/*
Controllers
*/
app.controller( 'appController', function( $scope ) {
});
app.controller( 'routeController', function( $scope, $routeParams ) {
//When route change, check if page has been updated and run animateScroll directive
if(typeof $routeParams !== 'undefined' && $routeParams.page.length > 0){
$scope.animateScroll($routeParams.page);
}
});
/*
Page routes
*/
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/home/:page', {
templateUrl: 'home-template',
controller: 'routeController'
})
.otherwise({
redirectTo: '/home/'
});
}]);
/*
Directives
*/
app.directive('scroll', function ($routeParams, $timeout) {
/*
Scroll to element ID
*/
return {
restrict: 'A',
link: function(scope, elm, attrs) {
scope.animateScroll = function(page) {
$timeout(function(){
console.log('test');
if(jQuery('#' + page).length == 1){
jQuery('html, body').animate({
scrollTop: jQuery('#' + page).position().top
});
};
}, 1);
};
}
};
});
app.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return { height: w.height() };
};
scope.$watch(scope.getWindowDimensions, function (dimensions) {
scope.windowHeight = dimensions.height;
scope.style = function () {
return {
'min-height': scope.windowHeight + 'px'
};
};
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
app.directive('a', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
elem.on('click', function(e){
e.preventDefault();
});
}
};
});
页面布局示例: