Created
October 8, 2013 15:44
-
-
Save alxhill/6886760 to your computer and use it in GitHub Desktop.
Updated version of Angular ScrollSpy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| angular.module('jobFoundryDirectives').directive 'spy', ($location) -> | |
| restrict: "A" | |
| require: "^scrollSpy" | |
| link: (scope, elem, attrs, scrollSpy) -> | |
| attrs.spyClass ?= "current" | |
| elem.click -> | |
| scope.$apply -> | |
| $location.hash(attrs.spy) | |
| scrollSpy.addSpy | |
| id: attrs.spy | |
| in: -> elem.addClass attrs.spyClass, | |
| out: -> elem.removeClass attrs.spyClass | |
| angular.module('jobFoundryDirectives').directive 'scrollSpy', ($window) -> | |
| restrict: 'A' | |
| controller: ($scope) -> | |
| $scope.spies = [] | |
| @addSpy = (spyObj) -> $scope.spies.push spyObj | |
| link: (scope, elem, attrs) -> | |
| spyElems = [] | |
| scope.$watch '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() | |
| # the elem might not have been available when it was originally cached, | |
| # so we check again to get another element in case this one doesn't exist. | |
| spyElems[spy.id] = | |
| if spyElems[spy.id].length is 0 | |
| elem.find('#'+spy.id) | |
| else | |
| spyElems[spy.id] | |
| # the element could still not exist, so we check first to avoid errors | |
| if spyElems[spy.id].length isnt 0 | |
| if (pos = spyElems[spy.id].offset().top) - $window.scrollY <= 0 | |
| 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
I did a JavaScript translation of this CoffeeScript and made a few updates. You can find the updates here: https://gist.github.com/EvilClosetMonkey/9194765
What changed:
spydefinition does not have an associated contentiddefined.spyitem if the browser is scrolled all the way to the bottom (content length sometimes prevent this from happening).activeto match Bootstrap's CSS.