Preface
I believe that friends who have used Angular should be correct$watch
This listening is no stranger. It is mainly used to monitor changes in the model. It will notify you when parts of your model change. I also used this awesome Angular in my recent platform management development, which I can't avoid using when making filters$watch
monitor. At that time, my idea was that I didn’t need to click the search button when searching, which was also excellent in user experience, avoiding the operation steps of clicking again after input.
Then, when$watch
The code was like this at the beginning when listening
$scope.$watch('filterOptions', function (newVal, oldVal) { if (newVal !== oldVal) { // When filterOptions changes, call the method $('admin/bill/'+$+'?pageCount='+$,$); } }, true);
Doing this seems to be nothing big, and you pull the data every time you enter it. but! but! but! Say important things three times! When the user enters the search word "Zhang San", the code is executed like this: the word "Zhang" pulls data once, and the word "San" pulls data once. OK, these are still two words. If you enter ten words, the server will cry and the server will come to the front end.
At this time, you need to use this product in Angular-$timeout
, he is a timer in angular. For our search, we are listeningfilterOptions
When there is a change, don't ask immediately and give it a waiting time of 0.8 seconds. If it is within 0.8 seconds.filterOptions
If there is no change again, then request to pull the data, otherwise continue to enter.
The code is as follows:
$scope.$watch('filterOptions', function (newVal, oldVal) { if (newVal !== oldVal) { if (timeout) $(timeout); timeout = $timeout(function() { $('admin/bill/'+$+'?pageCount='+$,$); }, 800); } }, true);
Summarize
The above is the entire content of this article. I hope it can help you study or work. If you have any questions, you can leave a message to communicate.