Update HTML input value changes in angular ng-mode

2019-07-09 03:42发布

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

4条回答
男人必须洒脱
2楼-- · 2019-07-09 04:23

Update the $scope rather than the DOM element.

$scope.val = 999;

查看更多
Explosion°爆炸
3楼-- · 2019-07-09 04:23

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.

查看更多
等我变得足够好
4楼-- · 2019-07-09 04:27

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

查看更多
男人必须洒脱
5楼-- · 2019-07-09 04:41

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)
查看更多
登录 后发表回答