Yahya Uddin
Yahya Uddin

Reputation: 28851

Angular Js ng-model not updating variable in an inner function

I have the following code in my controller:

appControllers.controller('myCtrl', [ '$scope',
function($scope) {
    $scope.timeFreeze = false;

    $scope.ws = new WebSocket("ws://localhost:8080/ws");

    $scope.ws.onopen = function() {
        $scope.ws.send('{...}');
    };

    $scope.ws.onmessage = function (evt) {
        var received_msg = JSON.parse(evt.data);
        //...do something with the data...
        console.log($scope.timeFreeze); // This is ALWAYS false!!! Why?
        if ( $scope.timeFreeze === false) {
            $scope.$apply();
        } else {
            console.log("Frozen!"); // This never runs!!!
        }
    };

    $scope.ws.onclose = function() {
        console.log("Connection is closed...");
    };
}

]);

and in my html I have:

<div>
    <label>Freeze?</label>
    <input type="checkbox" ng-model="timeFreeze"/>
</div>

What is meant to happen is that when the checkbox is ticked, the code should output "Frozen!" in the console. Unfortunately this code is NEVER run! The $scope.timeFreeze is always false despite me setting the ng-model for the checkbox.

Upvotes: 0

Views: 1131

Answers (1)

jeff
jeff

Reputation: 445

Posting the answer so it can be marked:

Try using dot notation. Something like ng-model="socket.timeFreeze" and $scope.socket.timeFreeze. JB Nizet used a better naming convention so I'm gong to borrow from him:

In your controller:

$scope.time = {freeze: false };

In your view:

<input type="checkbox" ng-model="time.freeze">

Upvotes: 1

Related Questions