Search code examples
javascriptangularjsangularjs-scope

AngularJS element.bind('resize') not updating $scope variable


I am trying to set a scope variable for the innerWidth of the browser window using the code below. It works when viewed in the console, but the function is not updating the $scope variable. Why?

angular.element($window).bind('resize', function () {
    console.log('resize', $window.innerWidth);  // I can see change here
    $scope.window_width = $window.innnerWidth;  // no change here
});

Solution

  • You're binding something with jQlite which lives outside Angular, so you manually have to invoke a $digest cycle here, otherwise Angular doens't know that there are changes.

    angular.element($window).bind('resize', function () {
        console.log('resize', $window.innerWidth);  
        $scope.window_width = $window.innerWidth; 
        $scope.$evalAsync(); 
    });
    

    $scope.$evalAsync() will call a digest cycle with a greater chance of firing inside the same js event tick then $timeout (more info here)