AngularJS 手动更新输入不会触发模型中的更改 [英] AngularJS update input manually does not trigger change in the model

查看:24
本文介绍了AngularJS 手动更新输入不会触发模型中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从纯 JavaScript 更改输入元素的值时,角度模型不会更新.有没有办法通过在更改后手动触发某些事件来以某种方式触发此更新?

When I am changing a value of an input element from plain JavaScript then the angular model is not updated. Is there any way to trigger somehow this update by firing some event manually after the change?

<body ng-controller="MainCtrl">
  <script>
    function changeValue() {
      var e = document.getElementById("field");
      e.value = "updated value";
    }
  </script>

  field: <input type="text" id="field" ng-model="field">{{field}}
  <br>
  <button onclick="changeValue()">Change the value</button>

</body>

完整示例可以在 plunkr 上找到.单击按钮后,我希望 {{field}} 以某种方式更新.有没有办法做到这一点?

Complete example can be found on plunkr. After clicking the button I would expect that the {{field}} is updated somehow. Is there a way doing this?

推荐答案

你不应该这样做(除非它用于测试,但即便如此,请考虑量角器).以这种方式与 angular 交互是一个坏主意.但是,如果您必须这样做,请按以下方式操作.

You should NOT be doing this (unless its for testing, but even then please consider protractor). Its a bad idea to being interacting with angular in this way. But if you MUST, here's how you do it.

function changeValue() {
  var e = document.getElementById("field");
  e.value = "updated value";
  var $e = angular.element(e);
  $e.triggerHandler('input');
}

PLNKR

<小时>

另一种中间方式是

PLNKR


A different middle way would be

function changeValue() {
  var e = document.getElementById("field");
  var scope = angular.element(e).scope();
  scope.field = "updated value";
  scope.$digest();
}

PLNKR

<小时>

正确的方法是使用角度控制器

PLNKR


The right way would be to use the angular controller

  $scope.changeValue = function(){
    $scope.field = "updated value";
  }; 

这篇关于AngularJS 手动更新输入不会触发模型中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆