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?
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.
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.
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.
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');
}
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();
}
The right way would be to use the angular controller
$scope.changeValue = function(){
$scope.field = "updated value";
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With