Gloria
Gloria

Reputation: 1053

Angular JS Controller to view binding not updating on window resize

Please see the fiddle: http://jsfiddle.net/HB7LU/4089/

On window resize if you check the console, $scope.showName keeps getting toggled between true and false as expected. However the view does not update. It remains with the initialized value of true. From my understanding, the {{}} or ng-bind provides 1 way binding from controller to the view, so the value in the view should update when it changes in the controller.

What am I missing?

Upvotes: 2

Views: 4838

Answers (5)

GianArb
GianArb

Reputation: 1674

http://jsfiddle.net/HB7LU/4094/

$scope.$digest();

Try with this code.. I have add $digest of scope alter resize

Upvotes: 0

kam
kam

Reputation: 425

     missing a call to $scope.$apply()

Look at http://jsfiddle.net/HB7LU/4093/

Upvotes: 0

shaunhusain
shaunhusain

Reputation: 19748

You are missing a call to $scope.$apply() since the event is being handled outside of an angular context you need to call $scope.$apply() to trigger a digest which will updated any watchers http://jsfiddle.net/HB7LU/4091/

function MyCtrl($scope, $window) {
    $scope.name = 'Timothy';
    $scope.showName = true
    $scope.nickname = 'Tim'

    angular.element($window).bind('resize', function() {
        if ($scope.showName){
            $scope.showName = false;
        }
        else
        {
            $scope.showName = true;
        }
        console.log($scope.showName);
        $scope.$apply();
      });
}

Upvotes: 1

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40298

You need to add $scope.$apply(); after any scope manipulation outside Angular events. Add it as the last statement of the bind function.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

The $scope only binds to the view on $digest cycles - your event doesn't trigger a digest cycle since there was no action taken. You have to call $scope.$apply() to trigger a view update.

Be warned tho, $scope.$apply() can throw an error if a $digest cycle is already in progress.

Upvotes: 6

Related Questions