2017-06-29 126 views
1

未定义我有一个事件处理程序,在我的AngularJS指令:的JavaScript - AngularJS范围问题:在全球范围内的对象在功能

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

在我的指令onScrollAction之前,我已经定义了一些变量,则onScrollAction功能之外本身,因为我不想让他们分配在每个车轮的事件,因为它们不应该改变。

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 

我的问题是,怎么来的elem是罚款从全球范围去功能范围,当theActiveElem是不是和我怎么解决它,所以我可以在我的事件处理程序做theActiveElem行动。

谢谢。

+0

的可能的复制[可变提升](https://stackoverflow.com/questions/3725546/variable-hoisting) – estus

回答

0

这真是怪我,想解释......在事件处理中

我的控制台日志看起来像:

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

但只要我改变了var theActiveElem = theObject[thepatch];theActiveElem = theObject[thepatch];它固定。

我承认,我不应该与var在该行宣布,但为什么会导致日志的几行了一个错误?

无论如何,这是现在已经得到解决。