I am new to AngularJS. I want to hide div "A" in AngularJS when a user scrolls on div "B". Currently I can hide the div "A" when user clicks on div "B" by using ng-click, but I could not find any way to do it with on scroll with AngularJS. I know, I can use JQuery to hide the div but is there any way to do it with AngularJS?
Update:
I created a scroll directive and attached it with $window. Now the div is hidden if I scroll the full window, but I want to hide it when a particular div is scrolled. My current implementation looks like bellow:
app.directive("scroll", function ($window) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset >= 10) {
scope.hideVs = true;
} else {
scope.hideVs = false;
}
scope.$apply();
});
};
});
I am not sure why you would want to do this but I created a jsfiddle with what I think you want.
I modified your directive slightly:
app.directive("scroll", function () {
return function(scope, element, attrs) {
angular.element(element).bind("scroll", function() {
scope[attrs.scroll] = true;
scope.$apply();
});
};
});
as you can see in now binds to the scroll event on the div not the window. I've also changed the variable it sets so that it takes the value provided to the scroll directive as the variable name.
http://jsfiddle.net/Tx7md/
Here is a version using $parse to set the value as suggested by @ganaraj
I'll assume for the moment that you don't want to use jQuery.
Using directives will not be a complete solution unless you're absolutely certain you can get a reference to div A from div B using only jqLite functions.
What you can do is create 2 directives: "do-hide-on-scroll" for div B, and "get-hidden-on-scroll" for div A. Using these, you catch the "scroll" event on div B, and use it to generate an Angular event using the $rootScope.emit
to send a "div B is scrolling" event to the top level parent scope. The parent scope, when it receives this, will $rootScope.broadcast
the same to all its children scopes, one of which is div A. Div A's "get-hidden-on-scroll" directive would have an event handler which listens for this event, then hides the div, and sets a $timeout for half a second to show the div again. If it receives the event again, it resets the timeout.
This is fairly convoluted, I agree, compared to just using jQuery. But at the end of the day, you're probably getting better performance. All in all, one of the harder nuts to crack purely with Angular. Good question!
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