Skip to content

Instantly share code, notes, and snippets.

@alxhill
Created October 8, 2013 15:44
Show Gist options
  • Save alxhill/6886760 to your computer and use it in GitHub Desktop.
Save alxhill/6886760 to your computer and use it in GitHub Desktop.
Updated version of Angular ScrollSpy
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()
@eddiemoore
Copy link

Thought I'd let you know that there is an issue with using $window.scrollY in Internet Explorer, it comes back as undefined. I know this cause i'm borrowing your code for a project i'm currently working on.
Found that if you use $window.pageYOffset then it will work in IE9+.
If you need IE8 as well then need to do something like $window.pageYOffset || $window.document.documentElement.scrollTop. Not sure what that code would be in coffeescript.

@kyranjamie
Copy link

Breaks in Anguar 1.2.0 onwards. Adds unnecessary return, ln:20.

@scottlingran
Copy link

Line 18 to 20 should be

controller: ($scope) ->
  $scope.spies = []
  @addSpy = (spyObj) -> $scope.spies.push spyObj
  return

Otherwise, CoffeeScript implicitly returns this.appSpy()

@walidvb
Copy link

walidvb commented Jan 13, 2014

If anyone is interested, I got this working for me, in JS, but it doesn't work within a ng-view(which was the purpose of this, making it work with dynamically added links?)

directive('scrollSpy', function($window) {
  return {
    restrict: 'A',
    controller: function($scope) {
      $scope.spies = [];
      $scope.test = 0;
      setTimeout(function(){console.log('$scope.test changed');$scope.test = 8}, 1000)
      this.addSpy = function(spyObj) {
        console.log('scroll added');
        $scope.spies.push(spyObj);
      };
    },
    link: function(scope, elem, attrs) {
      var spyElems = [];
      console.log(scope);
      scope.$watch('spies', function(spies) {
        console.log('$watch', spies);
        for (var _i = 0; _i < spies.length; _i++) {
          var spy = spies[_i];
          if (spyElems[spy.id] == null) {
            spyElems[spy.id] = (elem.find('#' + spy.id));
          }
        }
      }, true);

      $($window).scroll(function() {
        console.log(spyElems);
        var highlightSpy, pos, spy, _i, _len, _ref;
        highlightSpy = null;
        _ref = scope.spies;

        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          spy = _ref[_i];
          spy.out();
          console.log('spy',spy);
          spyElems[spy.id] = spyElems[spy.id].length === 0 ? elem.find('#' + spy.id) : spyElems[spy.id];
          if (spyElems[spy.id].length !== 0) {
            if ((pos = spyElems[spy.id].offset().top) - $window.scrollY <= 0) {
              spy.pos = pos;
              if (highlightSpy == null) {
                highlightSpy = spy;
              }
              if (highlightSpy.pos < spy.pos) {
                highlightSpy = spy;
              }
            }
          }
        }
        return highlightSpy != null ? highlightSpy["in"]() : void 0;
      });
    }
  };
}).
directive('spy', function($location) {
  return {
    restrict: "A",
    require: "^scrollSpy",
    link: function(scope, elem, attrs, scrollSpy) {
      console.log("scrollSpy," , scrollSpy);
      if (attrs.spyClass == null) {
        attrs.spyClass = "active";
      }
      elem.click(function() {
        scope.$apply(function() {
          $location.hash(attrs.spy);
        });
      });
      scrollSpy.addSpy({
        id: attrs.spy,
        in: function() {
          elem.addClass(attrs.spyClass);
        },
        out: function() {
          elem.removeClass(attrs.spyClass);
        }
      });
    }
  };
})

@garycuthbert
Copy link

Hopefully this may be of help to someone, it uses a retry mechanism to check the element sizes before applying the scroll positions, this addressed this issue of unpredictable ng-view page rendering in my application.

http://plnkr.co/edit/MRKo8e?p=info

@nwpappas
Copy link

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:

  1. Catch the case where a menu spy definition does not have an associated content id defined.
  2. Select the last menu spy item if the browser is scrolled all the way to the bottom (content length sometimes prevent this from happening).
  3. Changed the class to active to match Bootstrap's CSS.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment