2

I met a problem, a div is controlled by a value set in controller, if the value is true, then display it, it the value is false, then hide it. The value is controlled by the scroll event. The html code is as below:

<body ng-app="app" ng-controller="controller">
    <div class="round" ng-style="{'display':isRoundShow?'inline':'none'}"></div>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
    <h1>Hello Plunker!</h1>
</body>

The controller part is as below:

angular.module('app', [])

.controller('controller', function($scope) {
    $scope.isRoundShow = false;

    window.onscroll = function() {
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      if(scrollTop > 50) {
        $scope.isRoundShow = true;
      }else{
        $scope.isRoundShow = false;
      }
    }
})

The CSS definition is:

.round {
    width : 40px;
    height: 40px;
    background-color: #FF0000;
    border-radius: 50%;
    position: fixed;
    left: 10px;
    top: 10px;
}

Now I wonder why when I scroll, the round div never shows, I have built a plunker here : https://plnkr.co/edit/u8RHyCMYRR5L8BwouOkg?p=preview

1 Answer 1

2

It's because you are changing the values as part of a DOM event and the digest loop in angular isn't firing. I recommend finding a better way to do what you are trying to achieve here in the "Angular" way, but for now, you can force a digest using $apply(), as per my fork:

https://plnkr.co/edit/ihbiRtGebrIH81uqa6L3?p=preview

Sign up to request clarification or add additional context in comments.

1 Comment

FYI - Here is a similar question / answer stackoverflow.com/questions/20253322/angular-js-scroll-window

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.