-
Notifications
You must be signed in to change notification settings - Fork 19
/
ng-scrollto.js
106 lines (87 loc) · 2.98 KB
/
ng-scrollto.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Version 0.0.7
// AngularJS simple hash-tag scroll alternative
// this directive uses click event to scroll to the target element
//
// <div ng-app="app">
// <div ng-controller="myCtrl">
// <a scroll-to="section1">Section 1</a>
// </div>
// ...
// <div id="section1">
// <h2>Section1</h2>
// <a scroll-to="">Back to Top</a>
// </div>
// ...
// <div id="section1">
// <h2>Section1</h2>
// <a scroll-to="section1" offset="60">Section 1 with 60px offset</a>
// </div>
// </div>
angular.module('ngScrollTo', []);
angular.module('ngScrollTo')
.directive('scrollTo', ['ScrollTo', function(ScrollTo){
return {
restrict : "AC",
compile : function(){
return function(scope, element, attr) {
var handler = function (event) {
event.preventDefault();
ScrollTo.idOrName(attr.scrollTo, attr.offset);
};
element.bind("click", handler);
scope.$on('$destroy', function () {
element.unbind("click", handler);
});
};
}
};
}])
.service('ScrollTo', ['$window', 'ngScrollToOptions', function($window, ngScrollToOptions) {
this.idOrName = function (idOrName, offset, focus) {//find element with the given id or name and scroll to the first element it finds
var currentDocument = $window.document;
if(!idOrName) {//move to top if idOrName is not provided
$window.scrollTo(0, 0);
}
if(focus === undefined) { //set default action to focus element
focus = true;
}
//check if an element can be found with id attribute
var el = currentDocument.getElementById(idOrName);
if(!el) {//check if an element can be found with name attribute if there is no such id
el = currentDocument.getElementsByName(idOrName);
if(el && el.length)
el = el[0];
else
el = null;
}
if(el) { //if an element is found, scroll to the element
if (focus) {
el.focus();
}
ngScrollToOptions.handler(el, offset);
}
//otherwise, ignore
}
}])
.provider("ngScrollToOptions", function() {
this.options = {
handler : function(el, offset) {
if (offset) {
var currentDocument = el.ownerDocument;
var currentWindow = currentDocument.defaultView || currentDocument.parentWindow; // parentWindow is for IE8-
var currentScrollTop = currentWindow.pageYOffset || currentDocument.documentElement.scrollTop || currentDocument.body.scrollTop || 0;
var scrollToY = el.getBoundingClientRect().top + currentScrollTop - offset;
currentWindow.scrollTo(0, scrollToY);
}
else {
el.scrollIntoView();
}
}
};
this.$get = function() {
return this.options;
};
this.extend = function(options) {
this.options = angular.extend(this.options, options);
};
});