Affix Directive AngularJS
Demonstrating the need to unbind scroll events on routeChanges
HTML
<script type="text/ng-template" id="first-page.html">
<div>
<div class="before-block">
First Page
</div>
<div class="before-block">
First Page
</div><div class="before-block">
First Page
</div>
<div affixer class="sticky-block">Affix Element</div>
<div class="after-block">
<div>Tupacsum Ipsum And dreams of a world with the two of them are together, whatever. As long as when the check came they got first dibs. There was no mercy on the streets, I couldn't rest. Now ain't nobody tell us it was fair. it ain't no hope for tha future.</div>
<div>Suspended from school; and scared to go home, I was a fool. No money no babysitter, she couldn't keep a job. I wonder why we take from our women.</div>
<div>And dreams of a world with the two of them are together, whatever. Brenda got herself a boyfriend. But, Brenda's barely got a brain. Cause I bet Brenda doesn't even know. I blame my mother, for turning my brother into a crack baby.</div>
<div>And even though you're fed up. Suspended from school; and scared to go home, I was a fool. Call on the sirens, seen him murdered in the streets. From havin the world on his shoulders.</div>
<div>I was given this world I didn't make it. I reminice on the stress I caused, it was hell. As long as when the check came they got first dibs. Left me alone I grew up amongst a dyin breed.</div>
<div>We ain't meant to survive, cause it's a setup. Wonder why as I walk by. And dreams of a world with the two of them are together, whatever. I'm trapped inside a maze.</div>
<div>Tupacsum Ipsum And dreams of a world with the two of them are together, whatever. As long as when the check came they got first dibs. There was no mercy on the streets, I couldn't rest. Now ain't nobody tell us it was fair. it ain't no hope for tha...
CSS
.before-block {
background-color: red;
height: 100px;
width: 300px;
}
.after-block {
background-color: #c6c6c6;
width: 300px;
}
.sticky-block {
background-color:blue;
color: white;
height: 50px;
width: 100%;
}
JavaScript
var app = angular.module('siteController', []);
app.config( function ( $routeProvider ) {
$routeProvider
.when( '/', { templateUrl: 'first-page.html' } )
.when( '/second', { templateUrl: 'second-page.html' } );
});
app.directive('affixer', function ($window) {
return {
restrict: 'A',
link: function ($scope, $element) {
var win = angular.element($window);
var topOffset = $element[0].offsetTop;
function affixElement() {
console.log($window.pageYOffset);
if ($window.pageYOffset > topOffset) {
$element.css('position', 'fixed');
$element.css('top', '76px');
} else {
$element.css('position', '');
$element.css('top', '');
}
}
$scope.$on('$routeChangeStart', function() {
win.unbind('scroll', affixElement);
});
win.bind('scroll', affixElement);
}
};
})