Skip to content

Instantly share code, notes, and snippets.

@nh2
Last active December 16, 2015 21:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nh2/5501079 to your computer and use it in GitHub Desktop.
Angular scroll directive
# Updates a variable when the window scrollTop position is changed.
# Usage:
# <set-window-scroll set-variable="windowScroll"></set-window-scroll>
app.directive "setWindowScroll", ->
restrict: "E"
scope:
setVariable: "="
link: (scope) ->
$(window).scroll ->
# Need to call $apply here since we are changing the scope *asynchronously* (in scroll callback).
# See http://www.bennadel.com/blog/2449-Directive-Link-observe-And-watch-Functions-Execute-Inside-An-AngularJS-Context.htm
scope.$apply ->
scope.setVariable = $(window).scrollTop()
# Updates a variable when the window scrollTop position is changed.
# Usage:
# <set-window-scroll set-variable="windowScroll"></set-window-scroll>
app.directive "setWindowScroll", ->
restrict: "E"
scope:
setVariable: "="
link: (scope) ->
# Throttle to 300ms so that we don't call $apply so often.
throttled = _.throttle ->
scope.$apply ->
scope.setVariable = $(window).scrollTop()
, 300
$(window).scroll throttled
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment