patrickmarabeas / ng-ScrollSpy.js

An AngularJS module for navigation highlighting
http://patrickmarabeas.github.io/ng-ScrollSpy.js
MIT License
26 stars 9 forks source link

Add 'type' and 'id' to broadcast event #15

Open kmturley opened 8 years ago

kmturley commented 8 years ago

The broadcast event is useful to know when the enabled class is being added or removed from an element. However all broadcast events look the same.

I would suggest passing through the event type and id to the event for better access:

.factory('SpyFactory', ['$rootScope', function($rootScope){
  return {
    'spies': [],
    'addSpy': function(id) {
      var index = this.spies.map(function(e) { return e }).indexOf(id);
      if(index == -1) {
        this.spies.push(id);
        this.broadcast('addSpy', id);
      }
    },
    'removeSpy': function(id) {
      var index = this.spies.map(function(e) { return e }).indexOf(id);
      if(index != -1) {
        this.spies.splice(index, 1);
        this.broadcast('removeSpy', id);
      }
    },
    'broadcast': function(type, id) {
      $rootScope.$broadcast('spied', type, id);
    }
  }
}])

This then allows you to do know when the first element is selected and add a class (e.g. for a fixed nav)

$scope.fixedNav =  false;

$scope.$on('spied', function (event, type, id) {
    if (type === 'addSpy') {
        $scope.fixedNav =  true;
    } else if (type === 'removeSpy' && id === "content1") {
        $scope.fixedNav =  false;
    }
});

<nav ng-class="{fixed:fixedNav}"></nav>