AngularJS Input field not updated using setTimeout built-in controller

I am working with an AngularJS-enabled page, and I need to display the current clock in a read-only input text box (with two methods related to data-ng-model) . To simulate a running clock, I use the JavaScript scheduler with setTimeout to call a function every 1000 milliseconds, which updates the value of the $ scope'd property, which in turn is associated with this input text box. Somehow the value in the input field is not updated. So I placed the <pre /> tag and updated its contents using the jQuery selector. This works fine, so I need help to get the value of the input text field, which is also updated every second.

I installed jsFiddle for this example.

HTML below:

 <body data-ng-app="formApp"> <div data-ng-controller="FormCtrl"> Current Date and Time <input type="text" data-ng-model="formData.currentDateTime" readonly="readonly" size="60" /> </div> <pre id="currentDateTime" style="font-size:1.5em;"> </pre> </body> 

AngularJS application module and controller are declared as follows:

 (function() { var formApp = angular.module("formApp", []); formApp.controller("FormCtrl", function ($scope) { $scope.formData = {}; $scope.formData.currentDateTime = new Date().toString(); (function updateCDT() { $scope.formData.currentDateTime = new Date().toString(); document.getElementById("currentDateTime").innerHTML = $scope.formData.currentDateTime; setTimeout(updateCDT, 1000); })(); }); })(); 
+6
source share
4 answers

you need to use $scope.$apply() or $timeout angles to reflect the changes since setTimeout is beyond angularjs

using $ scope. $ apply ()

apply $ scope. $ apply () inside the anonymous function setTimeout (function () {}, 1000) and then call the actual function as shown below

  (function updateCDT() { $scope.formData.currentDateTime = new Date().toString(); document.getElementById("currentDateTime").innerHTML = $scope.formData.currentDateTime; setTimeout(function(){ $scope.$apply(); updateCDT() }, 1000); 

fiddle for $ scope. $ apply ()

using $ timeout (do not forget to enter it into the controller)

  (function updateCDT() { $scope.formData.currentDateTime = new Date().toString(); document.getElementById("currentDateTime").innerHTML = $scope.formData.currentDateTime; $timeout(updateCDT, 1000); })(); 

fiddle for $ timeout

+8
source

Instead of using setTimeout() you can use $timeout() , which will call $apply() internally, telling angular to start the digest.

Just remember to enter $timeout as a dependency

Demo

+3
source

If you change the scope outside of angular, as with setTimeout, you need to call $scope.$apply .

+2
source

Do the same as in the pre-tag:

 document.getElementById("input-field").value=$scope.formData.currentDateTime; 

Hope this helps!

+2
source

Source: https://habr.com/ru/post/985426/


All Articles