Skip to content

Instantly share code, notes, and snippets.

@developer88
Forked from axelav/scrollspy.coffee
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developer88/9047185 to your computer and use it in GitHub Desktop.
Save developer88/9047185 to your computer and use it in GitHub Desktop.
SpyOn Directive for AngularJS >= 1.2
#root { scroll-spy data-top-buffer="200" }
div spy="profile_info_part"
| Spy on profile info part and add 'active'class to this div
div
a name="profile_info_part" id="profile_info_part"
angular.module('directives.scrollSpy', [])
.directive('spy', ($location) ->
restrict: 'A'
require: '^scrollSpy'
link: (scope, elem, attrs, scrollSpy) ->
attrs.spyClass ?= 'active'
elem.click (e) ->
e.stopPropagation()
if attrs.spy
target = $('#' + attrs.spy)
speed = 750
$('html, body').stop().animate
scrollTop: target.offset().top + 1
speed
easeInOutCubuc = (x, t, b, c, d) ->
c * ((t = t / d - 1) * t * t + 1) + b
else
$('html, body').stop().animate scrollTop: 0, speed
scrollSpy.addSpy
id: attrs.spy
in: ->
elem.addClass attrs.spyClass
elem.parents('li').addClass attrs.spyClass
out: -> elem.removeClass attrs.spyClass
)
.directive('scrollSpy', ($window, $timeout) ->
restrict: 'A'
controller: ($scope) ->
$scope.spies = []
@addSpy = (spyObj) ->
$scope.spies.push spyObj
return
scope: true
link: (scope, elem, attrs) ->
spyElems = []
topBuffer = if attrs.topBuffer then attrs.topBuffer else 0
scope.$watchCollection 'spies', (spies) ->
for spy in spies
unless spyElems[spy.id]?
spyElems[spy.id] = elem.find('#' + spy.id)
$($window).scroll ->
highlightSpy = null
for spy in scope.spies
spy.out()
if !spyElems[spy.id]? or spyElems.length is 0
spyElems[spy.id] = elem.find('#' + spy.id)
if spyElems[spy.id]? and spyElems[spy.id].length isnt 0
# TODO: fix for IE9+ ?
# https://gist.github.com/alxhill/6886760#comment-952714
if (pos = spyElems[spy.id].offset().top) - $window.pageYOffset <= topBuffer
# if (pos = spyElems[spy.id].offset().top) - $window.scrollY <= topBuffer
spy.pos = pos
highlightSpy ?=spy
if highlightSpy.pos < spy.pos
highlightSpy = spy
highlightSpy?.in()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment