简体   繁体   中英

When JavaScript updates an input value, AngularJS filtering doesn't work

I'm trying to do some stuffs with Angular from a few days and I'm stucked with an update problem.

This is part of my HTML page :

<div ng-app="monApp" ng-controller="monControleur">
Date de début : <input type="text" ng-model="date_deb" placeholder="JJ/MM/AAAA" value="" name="date_d" id="champ_date_deb" size="12" maxlength="10">&nbsp;<span id="calendarMainDeb"></span>
<script type="text/javascript">
//<![CDATA[
    calInit("calendarMainDeb", "Calendrier Deb", "champ_date_deb", "jsCalendar", "day", "selectedDay","calendarWrap1");
//]]>
</script>
<table border='1'>
<tr data-ng-repeat="evenement in mydata | entre_deux_dates:date_deb:date_fin ">
....

When I input a new date_deb with the keyboard, displayed values are filtered with Angular. On the contrary, if a use a JS calendar to set the date_deb value, it sets the value but no filtering is realized unless giving focus in JS and pressing "space".

Here is the last part of the JS which updates the date value :

field.value = dateArr[0]+'/'+dateArr[1]+'/'+dateArr[2];
field.focus();

What can I do to dynamically update the filtered values right after a date is picked in the calendar ? I wouldn't like the user to have to press "space" after each selection ...

I have tried a lot of solutions in angular (ng-model-options, etc.) and in JS but none worked.

You need to invoke a digest cycle:

 $scope.$applyAsync(function() {
         field.value = dateArr[0]+'/'+dateArr[1]+'/'+dateArr[2]; 
         field.focus();
});

That is because angular works by dirty checking - in each digest cycle (apply means run a digest for the root scope), all watchers in the scope hierarchy are checked for changes, and updates occur as necessary.

You can put your answer in $timeout, as $timeout runs the digest cycle as well as it saves from the error "$apply alreay running".

$timeout(function() {
     field.value = dateArr[0]+'/'+dateArr[1]+'/'+dateArr[2]; 
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM