I am using angular js in my application. where in ng-change event i am calling webservice and based on the response rendering the html. but here in ng-change calls too frequently where we type fastly which causes browser to wait. this is not a problem in chrome and mozilla. can anyone help me here?
You could use a timeout and wait for the user to have finished typing before making a call to the server:
<input type="text" ng-model="some.thing" ng-change="fetchData()" />
app.controller('someCtrl', function ($scope, $timeout) {
var fetchDataDelay = 500; // milliseconds
var fetchDataTimer;
$scope.fetchData = function () {
$timeout.cancel(fetchDataTimer);
fetchDataTimer = $timeout(function () {
// make expensive call to the server...
}, fetchDataDelay);
};
});
Note that using Angular's $timeout
(instead of setTimeout/clearTimeout
) will take care of the Angular digest cycle for you (so you don't have to bother yourself with manually calling $apply()
or $digest()
).
I also faced a similar problem, I wanted to implement a debounced search. After a bit of headbanging, this is what I did :
Here is my input field marked with ng-model directive
<input ng-model="searchText" ng-model-options="{ debounce: 500 }" type="text" class="form-control" placeholder="Search...">
Please observe that I also included an ng-model-options="{ debounce: 500 }". It debounces the update to the underlying model by the specified number of milliseconds. Please refer to the documentation for ng-model-options directive here.
Now, I added a $watch like this :
$scope.$watch('searchText', function(newValue) {
// expensive ajax call
});
Please refer to the documentation of $watch here. It registers an event listener listening for any change in the expression passed as its first argument. In this case 'searchText', which is the model associated with my input field.
The debounce mentioned in the ng-model-options, debounces the update to the 'searchText' model and hence, it takes care of debouncing the ajax call(in my case).
Hope it helps. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With