2015-09-12 113 views
1

我怎样才能把这个jQuery代码为angularJs指令:移动元素的角度

http://jsfiddle.net/MMZ2h/4/

var lastScrollTop = 0; 
$("div").scroll(function (event) { 
    var st = $(this).scrollTop(); 
    if (st > lastScrollTop) { 
     $('img').animate({top: '-=10'}, 10); 
    } else { 
     $('img').animate({top: '+=10'}, 10); 
    } 
    lastScrollTop = st; 
}); 
+0

1.只是复制到角度控制器(使用与ID或类)。 2.做一个指令 –

+0

你想保持jQuery吗? – Jorg

回答

1

您不应在此处使用选择器,因为链接函数提供编译的DOM角度DOM。您可以像使用代码一样使用该DOM。 标记

<div scroll-div> 
    Content here 
</div> 

指令

app.directive('scrollDiv', function() { 
return { 
    link: function (scope, element, attrs) { 
     var lastScrollTop = 0; 
     element.scroll(function (event) { 
      var st = element.scrollTop(); 
      if (st > lastScrollTop) { 
       $('img').animate({ 
        top: '-=10' 
       }, 10); 
      } else { 
       $('img').animate({ 
        top: '+=10' 
       }, 10); 
      } 
      lastScrollTop = st; 
     }); 
    } 
}); 
+0

当然,感谢buddy – sani

+0

@sani很高兴帮助你..谢谢:) –

0

不知道您的标记是什么样子,你的应用程序被称为或,还有别的什么,只是像这样的东西应该工作:

angular.module('myApp') 
    .directive('myScroll', 
    ['$window', 'jQuery', 
     function($window, $) { 
      return { 
       restrict: 'A', 
       link: function ($scope, elem, attrs) { 
        $(elem).scroll(function (event) { 
         var st = $(this).scrollTop(); 
         if (st > $scope.lastScrollTop) { 
          $('img').animate({top: '-=10'}, 10); 
         } else { 
          $('img').animate({top: '+=10'}, 10); 
         } 
         $scope.lastScrollTop = st; 
        }); 

       } 
     }; 
}]); 

示例标记:

<div myScroll>This is just some stupid text unworthy of being read, so please don't waste 
    <br>your time reading this nonesense. 
    <br>Hey! why are you still reading this garbage? 
    <br>Stop reading now and start doing something useful, such as getting this leaf to move up 
    <br>while you scroll this page. 
    <br>On second thought, maybe just continue reading. 
    <br>This might be more productive then whatever 
    <br>it is you were doing before.</div> 

备注restrict: 'A'将指令限制为元素上的属性。 有关更多信息,请参见Angular Directive Docs