2015-09-12 144 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