Reputation: 305
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
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');
}
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";
};
Upvotes: 45