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

查看:218
本文介绍了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 被发现。点击该按钮后我会想到的是, {{}场} 以某种方式更新。有没有办法这样做呢?

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?

推荐答案

你不应该这样做(除非它的测试,但即使是这样,请考虑的 量角器 )。它是一个坏主意,被以这种方式与角度的互动。但是,如果必须,这里是你怎么做。

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天全站免登陆