最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular model doesn't update when changing input programmatically - Stack Overflow

programmeradmin0浏览0评论

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.

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">

Controller:

$scope.test_value = 'abc'; // starting value

Console:

$('#test_input').val('xyz');
$('#test_input').scope().$apply();
$('#test_input').scope().test_value;
-> 'abc';

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.

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">

Controller:

$scope.test_value = 'abc'; // starting value

Console:

$('#test_input').val('xyz');
$('#test_input').scope().$apply();
$('#test_input').scope().test_value;
-> 'abc';
Share Improve this question asked Jun 12, 2016 at 18:49 YarinYarin 184k155 gold badges410 silver badges524 bronze badges 3
  • Why are you not changing the value of $scope.test_value directly using console and rather doing it using jquery? – Rahul Arora Commented Jun 12, 2016 at 18:59
  • @RahulArora - This is demo code. I have an app where the input element is being updated programmatically, and I want the model to register that. – Yarin Commented Jun 12, 2016 at 19:05
  • Check my answer @Yarin – Rahul Arora Commented Jun 12, 2016 at 19:17
Add a ment  | 

1 Answer 1

Reset to default 8

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;
发布评论

评论列表(0)

  1. 暂无评论