以编程方式更改输入时,角度模型不会更新 [英] Angular model doesn't update when changing input programmatically
本文介绍了以编程方式更改输入时,角度模型不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个绑定到模型值的文本输入,但我无法弄清楚如何以编程方式更改输入值并将更改传播到模型。
I have a text input bound to a model value, but I can't figure out how to change the input value programmatically and have the change propagate to the model.
我理解,因为我正在更新角度范围外部的值,我需要显式调用 $ scope。$ apply()
,但它不起作用。
I understand that because I'm updating the value external to the angular scope that I need to explicitly call $scope.$apply()
, but it's not working.
HTML:
<input id="test_input" ng-model="test_value">
控制器:
$scope.test_value = 'abc'; // starting value
控制台:
$('#test_input').val('xyz');
$('#test_input').scope().$apply();
$('#test_input').scope().test_value;
-> 'abc';
推荐答案
ngModel侦听输入事件,所以你需要在设置值后触发该事件:
ngModel listens for "input" event, so you need to trigger that event after setting the value:
$('#test_input').val('xyz');
$('#test_input').trigger('input');
$('#test_input').scope().test_value;
这篇关于以编程方式更改输入时,角度模型不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文