-1

ng-change triggers immediately but I'd like to introduce some delay before sending request to server. I've read about the watch function but looks like there is no "simple" solution.

Any idea for quick refactoring to add simple delay on the following code?

$scope.searchOrder = null
$scope.change = (text) ->
  search_params = $scope.searchOrder
  $http.get('./api/orders?q=' + search_params).success( (data) ->
    $scope.orders = data
    console.log('Found matching order.')
    #console.log data
  ).error( ->
    console.error('No orders found.')
  )
olimart
  • 1,529
  • 3
  • 17
  • 32

3 Answers3

0

try:

var delayDuration = 200;
$scope.searchOrder = null
$scope.change = (text) ->
$timeout( ->
search_params = $scope.searchOrder
      $http.get('./api/orders?q=' + search_params).success( (data) ->
        $scope.orders = data
        console.log('Found matching order.')
        #console.log data
      ).error( ->
        console.error('No orders found.')
      ), delayDuration);

The code should be pretty self explanatory. It just uses the AngularJS timeout service. You should use this over the js setTimeout method so that angular is aware of when it completes.

Theo
  • 1,252
  • 17
  • 23
0

I believe I've answered this question in a tangential way here by creating a directive called ngDelay. This be implemented using ng-change in the normal way. Take a look, and see if it helps.

Community
  • 1
  • 1
Doug
  • 2,441
  • 2
  • 19
  • 22
0

You can utilize the debounce property ngModelOptions provides to achieve that very easy without using $timeout at all. Here's an example:

JS fiddle example

HTML:

<div ng-app='app' ng-controller='Ctrl'>
    <input type='text' placeholder='Type a name..'
        ng-model='vm.name'
        ng-model-options='{ debounce: 1000 }'
        ng-change='vm.greet()'
    />

    <p ng-bind='vm.greeting'></p>
</div>

JS:

angular.module('app', [])
.controller('Ctrl', [
    '$scope',
    '$log',
    function($scope, $log){
        var vm = $scope.vm = {};

        vm.name = '';
        vm.greeting = '';
        vm.greet = function greet(){
            vm.greeting = vm.name ? 'yo, ' + vm.name + '!' : '';
            $log.info(vm.greeting);
        };
    }]);
Max Sassen
  • 650
  • 5
  • 15