Sandeep Pal
Sandeep Pal

Reputation: 2185

Why Angular JS input model value does not get updated if i update value of input field using javascript ex: using setTimeout

I have a input field with model named "name" with some initialized value say "James".

And when i console $scope i can see model value as "James". ie. $scope.name = "James".

But immediate on next statement if i use setTimeout function and update input field value with Say "Marcus" and console $scope again, why i get $scope.name = "James" only.

I know, i have updated input field value by going out of box than angular and angular is not aware of updation.

So my real question is, Is Angular JS written over Javascript Language? And if yes, why using setTimeout not updated model value in $scope.

Please help me, if i am thinking/question is right or wrong.

Upvotes: 0

Views: 89

Answers (1)

Ahmed Wagdi
Ahmed Wagdi

Reputation: 934

This has to do with how angular handles two way data-binding and the digest loop. If you're interested in knowing all the details of how this works then you can read about it here: https://www.ng-book.com/p/The-Digest-Loop-and-apply/

The basic idea is that in angular the digest loop is used to keep track of all the variables you placed in your $scope. Whenever a variable changes it sets off the digest loop, in each cycle of the loop the new value of the variable is compared to the old value and updated accordingly until the new value is equal to the old value which ends the loop. That being said this only works as long as you change your variables within angular's context, this is especially true for changing variables within callback functions or with jquery. Angular doesn't know that a variable was changed so the digest loop never gets started, you could force it by using $scope.$apply but some cases should be avoided in general unless there's no angular alternative for it (Which usually isnt the case).

For setTimeout there's an angular alternative which is $timeout, this has the exact same functionality as setTimeout but it works within angular's context so your variable will be updated.

Upvotes: 1

Related Questions