Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is my HTML:

<input id="selectedDueDate" type="text" ng-model="selectedDate" />

When I type into the box, the model is updated via the 2-way-binding mechanism. Sweet.

However when I do this via JQuery...

$('#selectedDueDate').val(dateText);

It doesn't update the model. Why?

like image 881
Greg Avatar asked Aug 08 '12 21:08

Greg


3 Answers

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
   $('#selectedDueDate').val(dateText); 
});

See this to better understand dirty-checking

UPDATE: Here is an example

like image 71
Renan Tomal Fernandes Avatar answered Nov 04 '22 04:11

Renan Tomal Fernandes


Just use;

$('#selectedDueDate').val(dateText).trigger('input');
like image 31
Jan Kuri Avatar answered Nov 04 '22 05:11

Jan Kuri


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.

like image 17
Ben Taliadoros Avatar answered Nov 04 '22 04:11

Ben Taliadoros