2

I have some ng-model input elements that gets updated non-angularJS functions like jquery or sometimes by pure javascript DOM apis. The value on the html input element changes however the model scope variable doesn't get updated. Is there any way to force angular to process these updates

app.js
After a time-out of 5secs, the value 1 is changed to 999. This is reflected in html but not in $scope.val

 angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', '$timeout',function($scope,$timeout) {
     $scope.val = '1';
     $timeout(function(){
       document.getElementById("myid").value = 999;

     },5000)
   }]);

html

<form name="testForm" ng-controller="ExampleController">
  <input id="myid" ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
         <div>
           {{val}}
         </div>
</form>

I've also kept the code in plunker http://plnkr.co/edit/4OSW2ENIHJPUph9NANVI?p=preview

manikawnth
  • 2,739
  • 1
  • 25
  • 39
  • You may want to trigger an 'input' event from the input element after changing the value. Not sure, but that may get angular updated with the latest value. – HankScorpio Mar 29 '16 at 00:26

4 Answers4

1

Without triggering the update to 999 on some sort of change in the input you need to do this:

 angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', '$timeout',function($scope,$timeout) {
     $scope.val = '1';
     $timeout(function(){
       $scope.val = 999;

     },5000)
   }]);

you do not need to use anything like document.getElement(s).... in angular. Just set a new value on $scope.val

Here is the corrected Plunker:http://plnkr.co/edit/fWxMeNcJFtQreMKZaB5H?p=preview

omarjmh
  • 13,632
  • 6
  • 34
  • 42
1

Update the $scope rather than the DOM element.

$scope.val = 999;

shmuli
  • 5,086
  • 4
  • 32
  • 64
0

You can manually set the viewValue of the form element which will force the update.

$timeout(function(){
   var ele = document.getElementById("myid");
   ele.value = 999;

   $scope.testForm.anim.$setViewValue(ele.value);
 },5000);

See the updated plunkr.

David L
  • 32,885
  • 8
  • 62
  • 93
0

You can achieve this by,

$timeout(function(){
       document.getElementById("myid").value = 999;
       angular.element(document.getElementById("myid")).triggerHandler('change');
     },5000)

However the better approach would be to directly update the scope,

 $timeout(function(){
           angular.element(document.getElementById("myid")).scope().val = 999;
         },5000)
Low Flying Pelican
  • 5,974
  • 1
  • 32
  • 43