Reputation: 96
I would like fire a search after my user finish write (without a enter) in angularjs.
My html (simplified):
<div ng-class="input-append" ng-controller="searchControl">
<input type="text" ng-model="ajaxSearch" ng-change="search();">
</div>
My AngularJs (simplified):
$scope.searchControl = function() {
$scope.search = function(){
$http({
method: 'POST',
url: '<?php echo base_url('system/ajax_search/') ?>',
'data: search=' + $scope.ajaxSearch,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
$scope.result = data;
});
}
The original code is extensive, so i simplified. In my code, i post data always my user change the search. I would like post data seconds after my user stop to write.
Any ideas?
Upvotes: 1
Views: 2823
Reputation: 2482
This can be easily achieved with a directive:
angular.module('myApp', [])
.directive('keyboardPoster', function($parse, $timeout){
var DELAY_TIME_BEFORE_POSTING = 3000;
return function(scope, elem, attrs) {
var element = angular.element(elem)[0];
var currentTimeout = null;
element.onkeypress = function() {
var model = $parse(attrs.postFunction);
var poster = model(scope);
if(currentTimeout) {
$timeout.cancel(currentTimeout)
}
currentTimeout = $timeout(function(){
poster();
}, DELAY_TIME_BEFORE_POSTING)
}
}
})
.controller('testController', function($scope){
$scope.search = function() {
console.log("Executing query...");
}
})
And it can be used like this...
<div ng-app='myApp' ng-controller='testController'>
<input type="text" keyboard-poster post-function="search">
</div>
Use $timeout
and cancel each time user types; if the timeout runs, executes the scoped function given as an attr. You can modify the delay time to whatever fits better your user experience (I wouldn't drop it below 1000
though).
Upvotes: 4