19

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?

2
  • Why are you doing it this way instead of using ng-click and an angular controller? Commented Apr 8, 2014 at 16:15
  • I am trying to create a unit test / integration tests for a scenario, with this I can simulate user input. Commented Apr 9, 2014 at 8:28

1 Answer 1

45

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

Sign up to request clarification or add additional context in comments.

5 Comments

Of course, I plan to use this within a unit test and not in a production code.
Thanks for this. My use case was to create a bookmarklet to quickly log into my local development environment (with credentials that won't be used anywhere else, of course).
Out of curiosity, why is it horrible to do something like $(el).trigger('input')?
@MikeYoung for testing? or in production?
I looked over 4 different solutions for a workaround over this and this solution is the only one that works perfectly. Triggering over plain js doesn't work over angukar context has I read over the other solutions. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.