Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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';
like image 834
Yarin Avatar asked Jun 12 '16 18:06

Yarin


1 Answers

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;
like image 70
Rahul Arora Avatar answered Nov 05 '22 10:11

Rahul Arora