【问题标题】:Update HTML input value changes in angular ng-model更新 Angular ng-model 中的 HTML 输入值更改
【发布时间】:2016-07-16 08:44:31
【问题描述】:

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

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

【问题讨论】:

  • 您可能希望在更改值后从输入元素触发“输入”事件。不确定,但可能会使用最新值更新角度。

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


【解决方案1】:

在输入发生某种变化时不触发更新到 999,您需要执行以下操作:

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

     },5000)
   }]);

您不需要在角度中使用类似 document.getElement(s).... 的任何东西。 只需在 $scope.val 上设置一个新值

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

【讨论】:

    【解决方案2】:

    更新 $scope 而不是 DOM 元素。

    $scope.val = 999;

    【讨论】:

      【解决方案3】:

      你可以通过,

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

      但是更好的方法是直接更新范围,

       $timeout(function(){
                 angular.element(document.getElementById("myid")).scope().val = 999;
               },5000)
      

      【讨论】:

        【解决方案4】:

        您可以手动设置将强制更新的表单元素的 viewValue。

        $timeout(function(){
           var ele = document.getElementById("myid");
           ele.value = 999;
        
           $scope.testForm.anim.$setViewValue(ele.value);
         },5000);
        

        查看更新后的plunkr。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-26
          • 1970-01-01
          • 2017-11-10
          • 1970-01-01
          • 2016-12-09
          相关资源
          最近更新 更多