Reputation: 850
I want to change CSS elements while a user scrolls the angular way.
here's the code working the JQuery way
$(window).scroll(function() {
if ($(window).scrollTop() > 20 && $(window).scrollTop() < 600) {
$('header, h1, a, div, span, ul, li, nav').css('height','-=10px');
} else if ($(window).scrollTop() < 80) {
$('header, h1, a, div, span, ul, li, nav').css('height','100px');
}
I tried doing the Angular way with the following code, but the $scope.scroll seemed to be unable to properly pickup the scroll data.
forestboneApp.controller('MainCtrl', function($scope, $document) {
$scope.scroll = $($document).scroll();
$scope.$watch('scroll', function (newValue) {
console.log(newValue);
});
});
Upvotes: 29
Views: 37694
Reputation: 159105
Remember, in Angular, DOM access should happen from within directives. Here's a simple directive that sets a variable based on the scrollTop
of the window.
app.directive('scrollPosition', function($window) {
return {
scope: {
scroll: '=scrollPosition'
},
link: function(scope, element, attrs) {
var windowEl = angular.element($window);
var handler = function() {
scope.scroll = windowEl.scrollTop();
}
windowEl.on('scroll', scope.$apply.bind(scope, handler));
handler();
}
};
});
It's not apparent to me exactly what end result you're looking for, so here's a simple demo app that sets the height of an element to 1px
if the window is scrolled down more than 50 pixels: http://jsfiddle.net/BinaryMuse/Z4VqP/
Upvotes: 66