hello could you please how to show alert when scroll to top of div in angular js and same in when user scroll to bottom .Actually I know How to achieve this in jquery using if(this.scrollTop===0).But I am using ionic framework with angular js .So could could you please tell me how to get event when user scroll to top and show the alert .
here is my plunker http://plnkr.co/edit/8bqDi69oiBKTpDvCaOf6?p=preview
<body ng-controller="MyController">
<div style="width:90%;height:150px;border:1px solid red;overflow:auto;overflow-y: scroll">
<div ng-repeat="n in name">{{n.name}}</div>
</div>
You have to use a directive so that you connect your element to the backend.
I created a directive which is pretty similar to sebastionbarbier one without the bind part but I guess using link is doing pretty much the same as bind.
link: function(scope, element, attr) {
element.on('scroll', function() {
if(element[0].scrollTop == 0)
alert('show alert');
});
http://plnkr.co/edit/ra6HLvEsPBPHeNqVVI4c?p=preview
Angular will not provide you anything for this, you just need to bind a scroll event on your element. In my current project I have just created an event in my controller :
var container = angular.element(document);
container.on('scroll', function() {
if (container.scrollTop() > 1000) {
$('#scroll-top-button').addClass('show');
} else {
$('#scroll-top-button').removeClass('show');
}
});
// in your case angular.element(document) should be your div instead of document
It does perform very well (I would expect a if
on scroll event to cost some ressource but not really).
Easy way is to define a directive to bind a scroll event and look at position. Based on your code :
angular.module('ionicApp', ['ionic'])
.directive("scrollable", function() {
return function(scope, element, attrs) {
var container = angular.element(element);
container.bind("scroll", function(evt) {
if (container[0].scrollTop <= 0) {
alert('On the top of the world I\'m singing I\'m dancing.');
}
if (container[0].offsetHeight + container[0].scrollTop >= container[0].scrollHeight) {
alert('On the bottom of the world I\'m waiting.');
}
});
};
})
.controller('MyController', function($scope, $element) {
$scope.name = [{ ... }];
});
Then in your HTML just add the directive
<div scrollable style="width:90%;height:1...
I updated a version on your plunker (v5) which work for me and seems pretty strong for global compatibility. Did it low level ;)
If you want to implement some deeper feature you can use a library like waypoint
Waypoints is a library that makes it easy to execute a function whenever you scroll to an element. http://imakewebthings.com/waypoints/
It works really well too, is very light, and since v3.0 is jQuery free :D. I know some hardcore front-end designer using it without any performance issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With