1

I have a event handler in my AngularJS directive:

angular.element($window).on("wheel", onScrollAction);

Before onScrollAction in my directive I have defined some variables, outside of the onScrollAction function itself because I don't want them assigned on every wheel event, as they shouldn't change.

app.directive('scroll', function ($window) {
    return function(scope, element, attrs) {
    var elem = angular.element(document.querySelectorAll('.titletitle')).eq(1);
    var elemHeight = elem[0].scrollHeight;
    //so on until the 5th element
    //then object to store all the elements and their heights:
    var theObject = [{el:elem,elH:elemHeight},{el:elem2,elH:elem2Height},{el:elem3,elH:elem3Height},{el:elem4,elH:elem4Height},{el:elem5,elH:elem5Height}]
    var theActiveElem = theObject[0];
    var onScrollAction = function (event) {
    console.log(theActiveElem) //renders undefined
    console.log(elem) // renders the element

My question is, how come the elem is fine going from a global scope to a function scope, when theActiveElem is not and how do I fix it so I can do actions on theActiveElem in my event handler.

Thank you.

Graham
  • 7,431
  • 18
  • 59
  • 84
Summer Developer
  • 2,056
  • 7
  • 31
  • 68

1 Answers1

0

This is really weird to me, would like an explanation...

My console log inside the event handler looked like:

        console.log(theActiveElem,theObject); //theActiveElement undefined
        thepatch = Math.floor(theoffset/theActiveElem.elH)
        if(thepatch==1){
            var theActiveElem = theObject[thepatch];
            console.log(theActiveElem);
        }

But as soon as I changed the var theActiveElem = theObject[thepatch]; to theActiveElem = theObject[thepatch]; it fixed.

I recognize that I shouldn't have declared it with var on that line, but why would that cause an error in the log a few lines up?

Anyway, this is resolved now.

Summer Developer
  • 2,056
  • 7
  • 31
  • 68