unexpected behavior with two-way data binding in Angular

After carefully studying the Angular documentation, I decided to test a basic data binding concept.

Below is an example of the HTML file:

<body ng-app>
  <h1>Hello, world!</h1>
  <div ng-controller="Ctrl">
    <input type="text" ng-model="count" />
    COUNT: <span ng-bind="count"></span>
  </div>
</body>

Furthermore, here is the Ctrl function in JavaScript:

var i = 0;
function Ctrl($scope) {
  $scope.count = i;
  inc();
}

function inc() {
  i++;
  setTimeout(inc, 1000);
}

I initially expected that the "COUNT" in the HTML would continuously update as the variable "i" incremented every second in the JavaScript code.

However, my expectations were not met, and now I'm troubleshooting my code to identify any errors. I also aim to find a suitable example to effectively demonstrate two-way data binding - where changes made to a JavaScript object should reflect in the corresponding HTML elements.

Answer ā„–1

Here are two issues to consider:

  1. The statement $scope.count = i; does not reference the global i, so it will not update as expected (this is not specific to Angular).

  2. Your interval function updates the counter without Angular detecting it. To resolve this, consider using $apply or specialized Angular helpers like $timeout

A functional example would look like this:

(function (app, ng) {
  'use strict';

  app.controller('Ctrl', ['$scope', '$timeout', function ($scope, $timeout) {
    $scope.count = 0;

    (function _update() {
      $scope.$apply(function () {
        $scope.count += 1;
      });

      $timeout(_update, 1000);
    }());
  }]);
}(angular.module('app', []), angular));

View demo here: http://jsbin.com/unasaf/1/


Alternatively, a simpler version can be implemented:

function Ctrl($scope, $timeout) {
  $scope.count = 0;

  $scope.increment = function increment() {
    $scope.count += 1;
  };

  (function _update() {
    $scope.increment();    
    $timeout(_update, 1000);
  }());
}

Answer ā„–2

Check out this code snippet:

JavaScript Section:

function Counter($scope, $timeout) {
$scope.clickCount = 0;

$scope.incrementCounter = function(){
    $scope.clickCount++;
    $timeout(function(){
        $scope.incrementCounter();
    }, 1000);
}

$scope.incrementCounter();
}

HTML Section:

  
<body>
    <h1>Hello, world!</h1>
    <div ng-controller="Counter">
    <input type="text" ng-model="clickCount" />
    CLICK COUNT: <span ng-bind="clickCount"></span>
    </div>
</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

Utilizing a JavaScript variable within an HTML style attribute value

I have added some divs to a webpage. I am looking to adjust the width of these divs based on the browser or other settings. While I can manually set the width to 200px using inline styles, I need the flexibility to change it to 220px, 230px, or 240px depen ...

Connected with the functionalities of Umbraco Forms

Looking to develop a plugin similar to Umbraco Forms with identical functionality. Is it possible to incorporate custom fields from a database into the Umbraco backend's custom section and have them displayed on the frontend like Umbraco Forms? Seekin ...

Linking a Kendo widget to an HtmlHelper component through JavaScript in MVC/Razor

I am currently working on integrating an MVC ListBoxFor control with a Kendo MultiSelectFor to bind and update data. The goal is to have a list of users in the ListBox, and a list of available users in the MultiSelect box. When users are selected from the ...

Animating with React JS using JSON data sources

Currently, my project involves using React/Redux to store animation data in JSON and display it on a React page. The challenge lies in implementing the animations correctly while utilizing setTimeout for pauses and setInterval for movement. The Animation ...

Reactjs: Could someone provide a more detailed explanation of this statement?

After reading this line in the documentation here, I came across an interesting code snippet. this.setState({ chats: [...this.state.chats, data], test: '' }); It seems like we are adding to the 'chats' array in the state, but I&ap ...

Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received : [ { positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION ...

Tips for effectively utilizing foreach loops in JQuery

I've encountered an issue while displaying a list of data in a table using Smarty templates and foreach loops. I'm trying to make each line clickable to show new data below it, but currently, this functionality only works for the first line. Is t ...

Tips on utilizing the identical template in ngIf

I need to display different templates based on certain conditions. For example: <template [ngIf]="item.url.indexOf('http') == -1"> <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" > ...

Ensure that the navigation bar remains consistent when switching between pages

My issue lies within the React components I am working with. Essentially, my goal is to create a Single Page Application (SPA) using ReactJS. While setting up authentication using auth0-js, I also established some routes for navigation. The layout is stru ...

ThreeJS bringing Maya-style wireframe rendering to life

Currently, I am attempting to create a wireframe that will display quads instead of triangles by utilizing the following code: var geo = new THREE.EdgesGeometry( _this.geometry ); // or WireframeGeometry var mat = new THREE.LineBasicMaterial( { color: 0xf ...

What is the correct method for calculating the sum of one input field and multiple output fields?

I have a single input field and multiple calculated output fields using JavaScript :Click here to view the screenshot of the calculated problem You can see the live preview on this link: . When you visit this link, enter "Base on your annual bill amount: ...

The parameter did not successfully transfer to the internal function within Firebase Cloud Functions

I am currently working on a Firebase cloud function that looks like this: exports.foo = functions.database .ref("/candidates/{jobTrack}/{candidateId}") .onCreate((snap, context) => { const candidate = snap.val().candidate; const jobTrack = ...

When a barcode scanner is used, it will trigger a "keypress" event only if the user is currently focused on an input box. Is there a specific event to monitor when the user is not on an input

Scenario: In the development of my web application, I am utilizing a barcode scanner device that allows users to scan barcodes for navigation to specific pages. Challenge: The current barcode scanning device is set up to only trigger "keypress" events w ...

`ASP.NET utilized for displaying several pictures on a website`

My goal is to retrieve images from a database and showcase them on a webpage. I am looking to incorporate a "show more images" button in case there are too many images to display at once. Additionally, I would like for the additional images to load autom ...

Utilize API to import sunrise and sunset times based on specific coordinates directly into a Google Sheet

After countless hours of trying to crack this code, Iā€™m faced with a final hurdle. The challenge lies in parsing the output from the and storing either the sunrise or sunset time into a variable that can be exported as a result in a Google Sheet. The u ...

Update the background's color by cycling through a set of colors stored in

I have a container on my webpage with a light blue background, and I want the background color to darken progressively with each click. Currently, I am manually setting an array of colors for this purpose, but I am struggling to make the background color c ...

Is there a way for me to make my Note element automatically update whenever I modify its text content?

Feeling a bit stuck with my project, especially this part. I'm currently using React to develop a notes application, and I'm having trouble updating the note when changing the text within the modal popup. The commented sections are where I need h ...

Angular Nested Interface is a concept that involves defining an

Looking for guidance on creating a nested interface for JSON data like this: Any help is appreciated. JSON Structure "toto": { "toto1": [], "toto2": [], "toto3": [], } Interface Definition export interface Itot ...

Node.js: Issue with accessing external resources caused by incorrectly encoded GET parameter in URL?

When handling incoming client GET requests, I generate HTML pages based on the res.sendfile instruction. Everything has been working smoothly so far. However, I recently introduced a new extended GET route that includes a URL encoded parameter (verificati ...

Populate an array with the present date and proceed in reverse order

In my code, there is an array that has a specific structure: var graphData = [{ data: [[1, 1300],[2, 1600], [3, 1900], [4, 2100], [5, 2500], [6, 2200], [7, 1800]} I want to replace the numbers in the first element of each sub-array with the corresponding ...