简体   繁体   中英

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
});

you have done a silly mistake may be it when you typing the question.

 $scope.window_width = $window.innnerWidth; //innnerWidth should be innerWidth

and after you update the scope variable you need to run the digest cycle manually by calling $scope.$digest(); because resize is something happens outside of angular so we have to tell the angular to there is something to update in the scope.

what else we can use instead of $digest() ?

  1. you can wrapped the code in $timeout it will trigger the digest cycle it self

    $timeout(function() { $scope.window_width = $window.innerWidth; });

  2. use $scope.$apply(); like

    $scope.window_width = $window.innerWidth; $scope.$apply();

here is a demo

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 )

Try this :

$scope.$apply(function() { $scope.window_width = $window.innnerWidth; })

You bind a dom event, so must force an angular digest phase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM