Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

angularjs - How can I hide an element when the page is scrolled?

Ok, I'm a little stumped.

I'm trying to think the angular way coming from a jQuery background.

The problem: I'd just like to hide a fixed element if the window is not scrolled. If someone scrolls down the page I would like to hide the element.

I've tried creating a custom directive but I couldnt get it to work as the scroll events were not firing. I'm thinking a simple controller like below, but it doesnt even run.

Controller:

.controller('MyCtrl2', function($scope,appLoading, $location, $anchorScroll, $window ) {
   angular.element($window).bind("scroll", function(e) {
       console.log('scroll')
       console.log(e.pageYOffset)
       $scope.visible = false;
   })
})

VIEW

<a ng-click="gotoTop()" class="scrollTop" ng-show="{{visible}}">TOP</a>

LIVE PREVIEW http://www.thewinetradition.com.au/new/#/portfolio

Any ideas would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A basic directive would look like this. One key point is you'll need to call scope.$apply() since scroll will run outside of the normal digest cycle.

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
            scope.visible = false;
            scope.$apply();
        });
    };
});

I found this jsfiddle which demonstrates it nicely http://jsfiddle.net/88TzF/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...