AngularJS : ng-model binding not updating when changed with jQuery

AngularJS : ng-model binding not updating when changed with jQuery

This is my HTML:

When I type into the box, the model is updated via the 2-way-binding mechanism. Sweet.
However when I do this via JQuery…

It doesn’t update the model. Why?


Solution 1:

Angular doesn’t know about that change. For this you should call $scope.$digest() or make the change inside of $scope.$apply():

$scope.$apply(function() { 
   // every changes goes here

See this to better understand dirty-checking

UPDATE: Here is an example

Solution 2:

Just use;


Solution 3:

I have found that if you don’t put the variable directly against the scope it updates more reliably.

Try using some “dateObj.selectedDate” and in the controller add the selectedDate to a dateObj object as so:

$scope.dateObj = {selectedDate: new Date()}

This worked for me.

Solution 4:

Try this

var selectedDueDateField = document.getElementById("selectedDueDate");
var element = angular.element(selectedDueDateField);
element.val('new value here');

Solution 5:

Just run the following line at the end of your function:


Solution 6:

Whatever happens outside the Scope of Angular, Angular will never know that.

Digest cycle put the changes from the model -> controller and then from controller -> model.

If you need to see the latest Model, you need to trigger the digest cycle

But there is a chance of a digest cycle in progress, so we need to check and init the cycle.

Preferably, always perform a safe apply.

       $scope.safeApply = function(fn) {
            if (this.$root) {
                var phase = this.$root.$$phase;
                if (phase == '$apply' || phase == '$digest') {
                    if (fn && (typeof (fn) === 'function')) {
                } else {

          // your function here.