Reputation: 507
Hi I have an input field which is attached my model and when the user manually types into it a function is called upon change - this works fine and the model is reflecting as expected in the console log.
<input type="text" class="rating" ng-model="review.Rating" ng-change="change()" />
The issue I now have is that I have a second jQuery function which can be called by the User on the page which auto-populates the input field, but that doesn't seem to trigger an update of the model only the visual value of the input field.
I have therefore added to that second jQuery the following call to trigger an update (based on my research this should be correct)
$(".rating").trigger('input');
This seems to work fine in Firefox and Chrome as I have it reflecting the model in the console log however in IE (I have 11 - unsure of older browsers) the trigger input doesn't seem to work on updating the model.
Hope you can help.
Upvotes: 3
Views: 8529
Reputation: 25797
Since, you are updating the text field value outside of Angular's context, you need to tell Angular to reload the changes in $scope
. So if you have access to scope variable, directly call $apply()
after setting the value of input field via jQuyery:
$scope.$apply();
But if you don't have access to $scope
, you can use any of the parent element or the input field itself to get the scope:
Suppose your HTML looks like this:
<div id="foo">
<input type="text" class="rating" ng-model="review.Rating" ng-change="change()" />
</div>
Then do this:
angular.element(document.querySelector("#foo")).scope().$apply();
Upvotes: 2
Reputation: 1837
updated answer:
I think that it does not work, because Angular is probably not aware of the change. Try to call $scope.$digest() after you update the model or add the function inside of $scope.$apply(function() { $.....});
Instead of using jQuery, you can just add a function in your controller which assigns the value to the ng-model.
e.g.
<input type="text" ng-model="data.input" />
<button ng-click="autoFill()">Click me</button>
and in your controller
$scope.autoFill = function() {
$scope.data.input = "Hello World!";
};
Upvotes: 2