更新Angular ng模型中的HTML输入值更改 [英] Update HTML input value changes in angular ng-model
问题描述
我有一些ng-model输入元素,这些元素会获取更新的非angularJS函数,例如jquery或有时通过纯JavaScript DOM API获得. html input元素上的值会更改,但是模型范围变量不会更新. 有什么方法可以强制Angular处理这些更新
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
超时5秒后,值1更改为999.这反映在html中,但未反映在$ scope.val
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>
我也将代码保存在punker中 http://plnkr.co/edit/4OSW2ENIHJPUph9NANVI?p=preview
I've also kept the code in plunker http://plnkr.co/edit/4OSW2ENIHJPUph9NANVI?p=preview
推荐答案
您可以通过以下方式实现,
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)
这篇关于更新Angular ng模型中的HTML输入值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!