Update Angular ng-model view JS setTimeout

0
=
0
+
0
No specific Bitcoin Bounty has been announced by author. Still, anyone could send Bitcoin Tips to those who provide a good answer.
0

Hi,

I need to update my input using some interval. So I'm using following code:

HTML

<div ng-app="myapp">  
    <div ng-controller="MyCtrl">  
        <input type="text" ng-model="testVal" />
    </div>  
</div>

and JS:

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

app.controller('MyCtrl', function ($scope) {
   $scope.testVal = 0;

   setInterval(function() {
       $scope.testVal++;
   }, 1000);
});

When I'm debugging code then testVal is updated, but <input> have initial value.

Why?

1 Answer

1
=
0
=
$0
Internet users could send Bitcoin Tips to you if they like your answer!

You should use $timeout function from Angular.

Example:

var myapp = angular.module("myapp", []);

myapp.controller("MyController", function($scope, $timeout){
    $scope.testVal = 0;

    $timeout(function() {
        // Some code
        $scope.testVal++;
        $scope.apply(); // This function is updating your view, but it does not necessarily
    }, 3000);
});
SEND BITCOIN TIPS
User rating:

Thank you :)

1

Too many commands? Learning new syntax?

FavScripts.com is a free tool to save your favorite scripts and commands, then quickly find and copy-paste your commands with just few clicks.

Boost your productivity with FavScripts.com!

Post Answer