问题
I have some ng-model input elements that gets updated non-angularJS functions like jquery or sometimes by pure javascript DOM apis. The value on the html input element changes however the model scope variable doesn't get updated. Is there any way to force angular to process these updates
app.js
After a time-out of 5secs, the value 1 is changed to 999. This is reflected in html but not in $scope.val
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', '$timeout',function($scope,$timeout) {
$scope.val = '1';
$timeout(function(){
document.getElementById("myid").value = 999;
},5000)
}]);
html
<form name="testForm" ng-controller="ExampleController">
<input id="myid" ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
aria-describedby="inputDescription" />
<div>
{{val}}
</div>
</form>
I've also kept the code in plunker http://plnkr.co/edit/4OSW2ENIHJPUph9NANVI?p=preview
回答1:
You can achieve this by,
$timeout(function(){
document.getElementById("myid").value = 999;
angular.element(document.getElementById("myid")).triggerHandler('change');
},5000)
However the better approach would be to directly update the scope,
$timeout(function(){
angular.element(document.getElementById("myid")).scope().val = 999;
},5000)
回答2:
Without triggering the update to 999 on some sort of change in the input you need to do this:
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', '$timeout',function($scope,$timeout) {
$scope.val = '1';
$timeout(function(){
$scope.val = 999;
},5000)
}]);
you do not need to use anything like document.getElement(s).... in angular.
Just set a new value on $scope.val
Here is the corrected Plunker:http://plnkr.co/edit/fWxMeNcJFtQreMKZaB5H?p=preview
回答3:
Update the $scope
rather than the DOM element.
$scope.val = 999;
回答4:
You can manually set the viewValue of the form element which will force the update.
$timeout(function(){
var ele = document.getElementById("myid");
ele.value = 999;
$scope.testForm.anim.$setViewValue(ele.value);
},5000);
See the updated plunkr.
来源:https://stackoverflow.com/questions/36273385/update-html-input-value-changes-in-angular-ng-model