Pin header on top - With Angular

Simple directive to pin an element when it reaches the top of the screen (or a custom anchor with some tweaks)

by Luca De Nardi

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">

    <header id="head"></header>
    <section></section>
    
</div>

CSS

#page {
    height: 1000px;
}

header {
    display: inline-block;
    position:absolute;
    top: 50px;
    left: 0;
    width: 100%;
    height: 100px;
    background-color: grey;
}

section {
    height: 900px;
    background-color: lightgrey;
}

.min section {
    background-color: pink;
}

JavaScript

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        var pin = $('#head').offset().top;
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= pin) {
                 scope.boolChangeClass = true;
                 $('#head').css({
                     position: 'fixed',
                     top: 0
                 })
             } else {
                 $('#head').css({
                     position: 'absolute',
                     top: pin
                 })
                 scope.boolChangeClass = false;
                 console.log('Header is in view.');
             }
            scope.$apply();
        });
    };
});