André Baptista
André Baptista

Reputation: 522

AngularJS window scroll not updating scope

I lost a couple of hours due to this problem, I hope the solution saves time of someone.

The issue is in Angular 1.x, while trying to update the scope based on an scroll event, it doesn't get updated at all!

var app = angular.module("sample", []); 

app.controller("myCtrl", function($scope, $window) {
    $window.onscroll = function () {
        console.info($window.scrollY);

        $scope.scrollY = $window.scrollY;
    };    
});

CodePen here

Note that the event is triggered normally and the scrollY value is shown on the console perfectly. Even so the view doesn't reflect the scope change. That's frustrating. If you change the Name field, then the other properties gets updated.

Upvotes: 1

Views: 385

Answers (1)

André Baptista
André Baptista

Reputation: 522

The answer is simple, force the update of scope by using:

$scope.$apply();

Uncomment the corresponding line on the above code and see the magic happen.

It sounds simple, but get to this wasn't so fast.

I hope that helps someone.

Upvotes: 2

Related Questions