Trouble with updating Angular Js ng-model within a nested function

I am encountering an issue with the 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...");
    };
}

]);

In the html, I have included:

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

The expected behavior is that when the checkbox is checked, the console should output "Frozen!". However, this code block is never executed. The $scope.timeFreeze variable always remains false even after setting the ng-model for the checkbox.

Answer №1

Here is the answer that can be highlighted:

To access data using dot notation, you can use ng-model="socket.timeFreeze" and $scope.socket.timeFreeze. JB Nizet followed a better naming convention which I will also use:

Your controller should include:

$scope.time = {freeze: false };

In your view:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering problems with storing data containing diacritics in a Java REST API integrated with a MySQL database

I've been working on an app and I'm facing some challenges with handling data that contains diacritics or other UTF-8 characters. The specific characters causing issues for me are: ă-Ă-â-Â-î-Î-ş-Ş-ţ-Ţ. Initially, there is an input fiel ...

Is the image clickable to slide back and forth?

How can I achieve a sliding effect when clicking on the bottom-coupon class? Currently, I am only able to implement show and hide functionalities without any sliding effects. The picture slowly hiding from right to left, with the coupon-layer sliding out f ...

AngularJS allows for the creation of cascading dropdown selects, where the options in the second select

I'm struggling to access the version data stored in the server model, but it's not cooperating. My suspicion is that when the page loads, the initial data from the first select isn't available yet because it hasn't technically been sel ...

Exploring Angular modules has shed light on a certain behavior that has left me puzzled - specifically, when diving into JavaScript code that includes the

I am currently working with angularjs version 1.4.3 and I find myself puzzled by a certain segment of code in the Jasmine Spec Runner that has been generated. Upon generation, Jasmine (using ChutzPath) creates this particular piece of code: (function ...

Combine the values of properties in an object

I have a JavaScript object that contains various properties with string values. I want to concatenate all the property values. Here's an example: tagsArray["1"] = "one"; tagsArray["2"] = "two"; tagsArray["Z"] = "zed"; result = "one,two,zed" To prov ...

angular material theme malfunctioning

Within the configuration block, I have set up the following: .config(['$urlRouterProvider', '$stateProvider', '$locationProvider', '$mdThemingProvider', function ($urlRouterProvider, $stateProvider, $locationProvid ...

Copy files using grunt, in accordance with the ant pattern, while excluding any variable directories

My task is to transfer files from the src/ folder to the dist/plugin directory. Since the version can potentially change, I would like to exclude the version number in all instances. Here is what I currently have: files[{ cwd: 'src' src ...

Are you familiar with the concept of personal $pockets?

Why does Angular's $q store everything under the $$state object? I thought that double dollar sign conventionally represents private in Angular, so it seems odd to me in this situation. Is there a mistake in how I've set up my promise? I'm ...

Guide to simulating a scope in an Angular unit test using a directive instead of a controller

Recently, I have been working on understanding how to mock a $scope and controller using the $controller constructor. var scope = rootScope.$new(); it('should contain a testVar value at "test var home"', function(){ homeCtrl = $controller(&a ...

The reverse proxy in nginx is having trouble accessing custom paths within the loopback network

Running my loopback app on the server and attempting to access it via an nginx reverse proxy has been a challenge. Unfortunately, I'm quite new to nginx and struggling to configure it correctly. Below is a snippet from my config file /etc/nginx/sites- ...

Updating an element's HTML content from a template URL using AngularJS

Can someone help me figure out how to set the html of an element in my directive based on a dynamic template url? element.html('some url to a template html file'); rather than using element.html('<div>test</div>').show() ...

How can an AngularJS/Ionic mobile application incorporate an external JavaScript script?

Can external JavaScript scripts be executed in an AngularJS/Ionic mobile app, particularly on non-jailbroken iOS devices? We are considering creating a launcher version of our app that downloads the required scripts and then installs and runs them. I have ...

Configuring $scope.items for Angular Data Binding

I have a service that includes the following function, public object Get(AllUsers request) { var users = XYZ.GetAllUsers(); var userList = users.Cast<XYZ>(); return new AllUsers { UsersAcc = userList.Select(ConvertToEntity). ...

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...

Struggling to extract text from within a <p> tag on an Ionic 1 app page on iOS

After developing an ionic-1 application for iOS and Android devices, I encountered an issue with displaying mobile numbers in one of the views. The numbers are contained within <p> tags. While users can click and hold on a number to copy it on Andr ...

Applying the Directive/Isolated Scope as Embedded HTML within an Angular-Bootstrap Popover

If you're using the angular-ui popover, you have the ability to include HTML content within it. However, I encountered some difficulties in placing a directive called sampleDirective inside the popover. Despite my attempts with the $sce.trustAsHtml an ...

Utilize AngularJS to loop through a list with ng-repeat

Seeking guidance as an Angular newbie. The ng-repeat in question is formatted as: ng-repeat="f in drillDownList['D' + d.merchMetrics.DEPT_NBR + 'CG' + d.merchMetrics.CATG_GRP_NBR + 'C' + d.merchMetrics.DEPT_CATG_NBR] M ...

Tips for storing arrays in AngularJS with JavaScript

I am new to using JavaScript. I have a function that stores objects in an array to an Angular model. Here is an example: function getSpec(){ debugger var i; for(i=0;i<main.specifications.length;i++){ main.newProduct.Specification= ( ...

Creating a public API on an AngularJS directive for easy access from a controller!

I created a custom attribute directive and I'm looking to create an API for that directive that can be accessed from the controller. Previously, I followed the advice given in the top answer of this question. However, it seems like that method is no ...

Maintaining Styles After Focus is Removed in CSS: A Guide

The CSS that styles our buttons is as follows: .btn-outline-primary { color: blue; border: 1px solid blue; background: transparent; transition: all 0.3s ease 0s; } .btn-outline-primary:hover, .btn-outline-primary:focus { background: ...