Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS update input manually does not trigger change in the model

Tags:

angularjs

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?

like image 481
reluxa Avatar asked Apr 08 '14 16:04

reluxa


People also ask

How do you Manually trigger change detection?

We can trigger change detection manually by using detectChanges() , ApplicationRef. tick() , and markForCheck() that we mentioned earlier on AsyncPipe . detectChanges() on ChangeDetectorRef which will run change detection on this view and its children.

What are the ways to trigger change detection in Angular?

True "manual" change detection in Angular would be a combination of the OnPush change detection strategy with methods like detectChanges(), detach(), markForCheck() and others in your components. This can be a great solution if you need full control over change detection.

What is Ng Onchange?

ngOnChanges()link A callback method that is invoked immediately after the default change detector has checked data-bound properties if at least one has changed, and before the view and content children are checked.


1 Answers

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

like image 194
Fresheyeball Avatar answered Nov 08 '22 09:11

Fresheyeball