6

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';
3
  • Why are you not changing the value of $scope.test_value directly using console and rather doing it using jquery? 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. Commented Jun 12, 2016 at 19:05
  • Check my answer @Yarin Commented Jun 12, 2016 at 19:17

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Side note: You do not need the $apply() call when using trigger, and jQuery has to be included before Angular in order for it to work: jsfiddle.net/xj9rysy6
What if I'm working in an 'input' event? wouldn't triggering the input again cause an infinite loop?
then you dont need to trigger it, you just need to call the scope() for angular to digest it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.