Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing css on scrolling Angular Style

Tags:

angularjs

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);
    });
});
like image 658
spracketchip Avatar asked Nov 25 '12 07:11

spracketchip


1 Answers

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/

like image 95
Michelle Tilley Avatar answered Sep 19 '22 15:09

Michelle Tilley