What causes the lack of synchronization between AngularJs scope-checkbox and its inner properties?

Solved Make sure to utilize Angular's $timeout function instead of the native setTimeout method

I have a property in my model that is displayed as a checkbox. I also have a $scope.watch function that monitors changes to this property and takes action based on its state.

However, when checking the value, it seems to show the old value.

Here is a sample and instruction: https://jsfiddle.net/L1f37px4/12/ HTML:

<div ng-app="hangarApp" ng-controller="hangarController">
  <input type="checkbox" ng-model="showOnlyPremiums" id="showPremId">
  <label for="showPremId">ClickMe</label>
  <div>{{showOnlyPremiums}}</div>
  <textarea readonly="readonly">{{testVar}}</textarea>
<p>
step 1. not checked? yes, false<br>
step 2. click it! and?.. only higher value changed<br>
step 3. surprise! click anywhere on free place. lower value changed too<br>
step 4. clicks more not repeat this. but values are not syncs....<br><br>
w.t.f???
</p>
</div>

JS:

(function() {
  'use strict';

  var hangarApp = angular.module('hangarApp', []);

  // CONTROLLER
  hangarApp.controller('hangarController', function($scope, $timeout) {
    $scope.showOnlyPremiums = false;
    $scope.testVar = $scope.showOnlyPremiums;
    $scope.$watchGroup(['showOnlyPremiums'], function() {
      // watcherByChanges();
      $scope.$broadcast('myCustomEvent', {});
    });
    $scope.$on('myCustomEvent', function(event, data) {
      $timeout(function() {
        $scope.testVar = $scope.showOnlyPremiums;
      });
    });

  });

})();

Using AngularJs 1.6

PS: Apologies for any language errors in my English

Answer №1

When you find yourself using $timeout, it is often considered a warning sign or "code smell" indicating a deeper underlying issue. Not only that, but it can also lead to unnecessary browser render cycles, potentially causing unwanted flickering on the screen.

Instead of relying on watchers and $timeout, consider utilizing the ng-change directive to respond to user input changes:

<input type="checkbox" ng-model="showOnlyPremiums" 
       id="showPremId" ng-change="onBoxCheckChange(showOnlyPremiums)" />
$scope.onBoxCheckChange = function(value) {
    $scope.testVar = value;
};

The ng-change directive seamlessly integrates with AngularJS's framework and digest cycle. Any operations performed within the AngularJS context will benefit from features like data-binding, property watching, and exception handling.


The DEMO

angular.module("app",[])
.controller("ctrl", function($scope) {
    $scope.onBoxCheckChange = function(value) {
        $scope.testVar = value;
    };
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
    <input type="checkbox" ng-model="showOnlyPremiums" 
           id="showPremId" ng-change="onBoxCheckChange(showOnlyPremiums)" 
    /> Show Only Premiums
    <br>
    testVar={{testVar}}
</body>

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

Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a ...

AngularJS ui-rangeSlider when the handle is released

Below is the HTML code snippet: <div range-slider min="0" max="100" model-max="rangevalue.value" pin-handle="min" onHandleUp="x()"></div> I am trying to achieve the following: $scope.x=function(){ console.log($scope.rangevalue.value) } How ...

I am experiencing difficulties with broadcasting and attending events

File.js scope.menuItemClick = function (def, callbackText, keepMenuOpen) { console.log(def); if(def.automationId === "Print"){ console.log("before send"); $scope.$root.$broadcast("printingData","my Data"); console.log("after send"); } Nex ...

Elasticsearch's fuzzy search feature is not providing any suggestions

I'm currently working on implementing a fuzzy/autocomplete search feature in Elasticsearch using NodeJS. The data has been indexed under the "artist" index. Here's an example of some stored data in ES. { "hits": [{ "_index": "artist", ...

Using jQuery to loop through a table and retrieve the button value from every row

I have a challenge with dynamically created buttons in a table. My goal is to loop through the table, identify the rows that have a checked checkbox, and retrieve the value of a button within that row. I then need to store these values in an array. Unfortu ...

A guide on leveraging *ngFor in Angular 4 to assemble a table featuring 2 columns in every row

I have an array of objects as shown below let columns = [ {id: 1, columnName: 'Column 1'}, {id: 2, columnName: 'Column 2'}, {id: 3, columnName: 'Column 3'}, {id: 4, columnName: 'Column 4'} ]; My ...

Utilizing the dynamic flair with React's map functionality

In my display area, which is a div element, I have rendered some text using spans. I utilized the map function to render the text from an array. The issue arises when I apply a color class to the span elements within the map function, causing all text to ...

Instructions on how to extract and display the key-value pairs from a nested JSON array in Angular 2, then populate them in a select box

My goal is to extract data from a Json data model and populate a select box with the data as drop-down items. However, I am encountering difficulties in achieving this as the entire Json array is being printed instead of just the 3 major headings that I wa ...

Version 2.7.2 of Chart.js now allows users to retrieve the value of a data point by

I need to retrieve the value for each point clicked on, but I am currently only able to get the value of the first line when I click on a point. The GetElementsAtEvent function provides me with an array of 3 active elements, but how can I specifically extr ...

Return the information from Node.js to the JavaScript on the client side

My goal is to establish a fetch connection from client-side JS to the server Node.JS. When a person clicks on a button in HTML, it triggers a search in the MongoDB database on the server side. Once the element is found, I am unsure how to send that informa ...

Tips for altering the scrolling rate of a container

I am trying to adjust the scroll speed of specific divs among a group of 5 divs. I came across a solution that changes the scroll speed for the entire document: http://jsfiddle.net/36dp03ur/ However, what I really need is a scenario like this: <div i ...

Showing a DataTable row within a pop-up modal

I'm facing an issue with rendering datatable content inside a modal after setting up the datatable and modal for row click functionality. I need each column of the row to display information under a unique span class. Below is my HTML structure. The ...

What are the potential drawbacks of dynamically generating a form within an Angular controller?

Currently, I am handling this task within a controller: $scope.logout = function() { var logout_form = document.createElement("form"); logout_form.setAttribute("method","post"); logout_form.setAttribute("action","logout"); document.body. ...

Three.js Photometric Function

Is there a way to specify a photometric function in Three.js? Currently, I am utilizing a Lambert material: new THREE.MeshLambertMaterial({ color: 0xffffff }) However, I am interested in using a Lommel Seeliger but I am unsure of the process and locatio ...

Aggregate the array of objects into a new array and calculate the total sum of values

I have an array with the following structure, and I am attempting to separate objects into a new array by grouping two values. Array: [ { "year": "202003", "cost": 11194.55, "type": "A" }, ...

Incorporating map() with data passed down as props from App.js into child components

I have React version 18.2 and I want the child component in App.js to receive data and utilize the map() function. Although the child component successfully receives the data, it is encountering an issue when trying to use map(). An error message is disp ...

Nextjs server encountered an issue where it was unable to connect to the localhost

npm run dev > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="563239352239247b372626393f38223b3338227b3439393d3f38317b2133347b372626166678677866">[email protected]</a> dev > next dev ▲ Next.js 14.2. ...

Cancellation of event by keypress handler

I found this code snippet: jQuery('#parent').on('keypress', '.textbox', function(e) { var btn = jQuery(this).closest('tr').find('.btn'); if (btn.length) { btn.triggerHandler('click&apo ...

Exported excel files cannot contain multiple footer rows in Datatable

Currently, I'm working on creating a Datatable Excel file that can support multiple footers along with an export option. However, I've run into an issue where the footer is only being generated in a single cell without support for multiple lines ...

Retrieve the information in a div element from an external website by utilizing AJAX

Exploring the world of AJAX is new to me, and I am eager to fetch content from a div on an external site and display it on my own website. Below is the current code snippet I have: <html> <head> <script src="https://ajax.googleapis.com ...