reluxa
reluxa

Reputation: 305

AngularJS update input manually does not trigger change in the model

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>

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?

Upvotes: 19

Views: 31119

Answers (1)

Fresheyeball
Fresheyeball

Reputation: 30015

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


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


The right way would be to use the angular controller

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

PLNKR

Upvotes: 45

Related Questions