javascript - 更新 Angular ng-model 中的 HTML 输入值更改

标签 javascript angularjs angularjs-scope angular-ngmodel angularjs-ng-model

我有一些 ng-model 输入元素,它们可以更新非 angularJS 函数,例如 jquery,或者有时通过纯 javascript DOM api。 html 输入元素上的值发生更改,但模型范围变量不会更新。 有没有办法强制 Angular 处理这些更新

app.js
超时 5 秒后,值 1 更改为 999。这反射(reflect)在 html 中,但未反射(reflect)在 $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>

我还将代码保存在 plunker 中 http://plnkr.co/edit/4OSW2ENIHJPUph9NANVI?p=preview

最佳答案

如果输入中发生某种变化而不会触发更新到 999,您需要执行以下操作:

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

     },5000)
   }]);

你不需要在 Angular 中使用像 document.getElement(s).... 这样的东西。 只需在 $scope.val

上设置一个新值即可

这是更正后的 Plunker:http://plnkr.co/edit/fWxMeNcJFtQreMKZaB5H?p=preview

关于javascript - 更新 Angular ng-model 中的 HTML 输入值更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36273385/

相关文章:

javascript - 使用 jQuery 添加/删除多个输入类型文本

javascript - 溢出在单词的开头,或在后续文本的末尾,直到下一次出现

javascript - 图表不是绘图

angularjs - 在 Angular 中如何使用 Controller 功能更改路由模板?

angularjs - $state 在 Angular 路由中解决 promise 时未填充

angularjs - Angular 更新和清除工厂变量

JavaScript 代码安全

angularjs - Angular 资源编码 URL

javascript - 使用 AngularJs 制作月度出勤报告

javascript - 我的 li 范围没有在 Angular js 中删除为什么?