Reputation: 3021
I generally hate asking questions like this, but I am new to Angular and trying to wrap my head around all of the concepts. One aspect that is tricky to me is how different areas of the page interact with one another.
In my example, I have site whereby I need to add a particular classname to the body element when the page is scrolled X pixels. X being the height of a particular element.
In jQuery, it might look like this:
$(window).scroll(function() {
var top = $(window).scrollTop();
if (top > ($('#header').height())) {
$('body').addClass('scrolled');
} else {
$('body').removeClass('scrolled');
}
});
In Angular, I'm not sure where to begin. A custom directive on the body tag? Does anyone have any suggestions or resources about this general type of problem I might look at?
Upvotes: 3
Views: 1817
Reputation: 19718
Using a directive for such tasks is a perfect match. I've created a Fiddle to demonstrate how to use this.
The code of your directive can be as simple as this (no jQuery):
angular.module("app").directive("scroll", function () {
return {
link: function (scope, element) {
element[0].addEventListener("scroll",function (event) {
var header = document.getElementById("header"),
body = document.getElementById("scrollMe");
if (body.scrollTop > header.offsetHeight) {
body.classList.add("scrolled");
} else {
body.classList.remove("scrolled");
}
});
}
}
});
I suggest reading up on the Angular docs and watching the egghead tutorial videos. They are a great help when starting with Angular development.
Also, this article sums up nicely why you shouldn't be afraid of using directives.
Upvotes: 1