AngularJS custom directive and controller method are attached to md-fab scroll-back-to-top button. The md-fab button is made visible as soon as page is scrolled down and gets hidden when pages reached top. My problem is custom directive not working therefore md-fab button is not made visible on scrolling down. If I change md-button css property visibility to visible and scroll page down then on clicking md-fab button does not respond to scroll back to top of the page.
I started facing this problem since I only reshuffled the same working code in index.html file.
I am unable to trace this problem for a few days. Appreciate some expert guidance to fix this issue telling where I am going wrong.
mainCtrl method
(function() {
angular.module('mainApp')
.controller('mainCtrl', function($scope, $window) {
$scope.scrollTop = function () {
$window.scrollTo(0, 0);
};
}
})();
Custom Directive
(function() {
angular
.module("mainApp")
.directive("scrollToTop", function ($window) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
angular.element($window).bind("scroll", function() {
if (this.pageYOffset > 0) {
element.css({visibility: 'visible'});
} else {
element.css({visibility: 'hidden'});
}
});
}
}
});
})();
HTML
<body layout="row" ng-controller="mainCtrl" ng-cloak>
<md-sidenav>
</md-sidenav>
<main layout="column" flex aria-hidden="false">
<md-toolbar layout-padding class="app-toolbar">
</md-toolbar>
<md-content md-scroll-y flex>
<div ui-view flex="noshrink" ng-hide="data.error">
</div>
<div flex="noshrink" ng-show="data.error">
</div>
<button
type="button"
class="md-fab md-fab-bottom-right md-button md-ink-ripple"
draggable scroll-to-top
ng-click="scrollTop()"
style="position: fixed; visibility: hidden;" aria-label="Back to Top">
<md-tooltip>Draggable Scroll Back to Top</md-tooltip>
<md-icon md-svg-src="img/material/ic_expand_less-24px.svg" aria-hidden="scrollBackToTop button">
</md-icon>
</button>
</md-content>
</main>
</body>`
You do not have the window scrolling because the scrolling is taken care of by
md-contentof angular material, so please change your code to handle the scroll ofmd-contentinstead of the window!Note: The JS fiddle works, I am adding the snippet for code reference!
jsfiddle