Animal Style
Animal Style

Reputation: 709

Input using ng-model not binding when textbox is populated via javascript

I have a text box that gets populated using javascript that is getting the data by reading a QR code and setting the value. I am using ng-model to bind to a variable in my controller which works fine when I type manually into the text box just not when it is populated with javascript. I am guessing there is some event I have to manually fire to trigger ng-model to do it's magic but I do not know what that event is or if it is even the right approach. My input looks like:

<input type="text" id="read" name="itemId" class="form-control center-block" placeholder="Item Id" ng-model="scannedId"/>

I am setting the value with the following once the QR code reading javascript does it's thing and works:

$('#read').val(data);

I have tried the following to try and manually trigger an event I hoped ng-model would be listening for right after assigning val(data) but both fail:

$('#read').trigger('input');
and
angular.element($('#reader')).triggerHandler('onChange');

Everything works fine if I type in it manually just not when updated with javascript. Thanks in advance!

Upvotes: 0

Views: 3955

Answers (2)

Hitmands
Hitmands

Reputation: 14159

When you're outside from the AngularJS Environment you need to manual trigger the DigestCycle... So, try something like that:

var scope = $('#read').scope(); scope.apply(function() {scope.scannedId = 'new value outside AngularJS LifeCycle'; });

Upvotes: 0

daleyjem
daleyjem

Reputation: 2674

Set the model value inside of your controller. Don't use jQuery.

Inside of your controller, create an object: $scope.myModel = {};

Then change your ng-model="myModel.scannedId"

Then inside of your controller, you can set the model $scope.myModel.scannedId = data and it will automatically bind.

Lesson being... Don't try to explicitly set 'value' with jQuery, especially if you have the ngModel directive on it. Somehow Angular overrides this, even when you can see the 'value' attribute has changed.

Upvotes: 2

Related Questions