更新 angular ng-model 中的 HTML 输入值更改 [英] Update HTML input value changes in angular ng-model
问题描述
我有一些 ng-model 输入元素可以更新非 angularJS 函数,例如 jquery 或有时通过纯 javascript DOM apis.html input 元素上的值会发生变化,但模型范围变量不会更新.有什么方法可以强制 angular 处理这些更新
app.js
超时 5 秒后,值 1 更改为 999.这反映在 html 中,但未反映在 $scope.val
angular.module('inputExample', []).controller('ExampleController', ['$scope', '$timeout',function($scope,$timeout) {$scope.val = '1';$超时(功能(){document.getElementById("myid").value = 999;},5000)}]);
html
</表单>
我也将代码保存在 plunker 中http://plnkr.co/edit/4OSW2ENIHJPUph9NANVI?p=preview
您可以通过,
$timeout(function(){document.getElementById("myid").value = 999;angular.element(document.getElementById("myid")).triggerHandler('change');},5000)
然而,更好的方法是直接更新范围,
$timeout(function(){angular.element(document.getElementById("myid")).scope().val = 999;},5000)
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
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-model 中的 HTML 输入值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!