0

I was wondering if you could help. I have the below code which sets a timeout delay before making a http request. The watch is bound to a input box. This is currently in my controller and it works.

    $scope.$watch('query.keyword',function($http){
    var searchInput = document.getElementById('searchInput').value;
    var minLength = 3;
    var req;

    if (timeout) {
        clearTimeout(timeout);
    }

    timeout = setTimeout(function(){
        var newValue = searchInput;
        if(newValue !== null && newValue.length > minLength) {
            window.alert(newValue);
            req = {
                method: 'SET',
                url: ''
            };
        }
    }, 3000);   
    return $http(req);
});

Now I want this as a factory/service to call upon rather than listing it in my controller.

I then made this...

app.factory('sendSearchData', function($http) {
    var searchInput = document.getElementById('searchInput').value;
    var minLength = 3;
    var req = null;

    if (timeout) {
        clearTimeout(timeout);
    }

    timeout = setTimeout(function(){
        var newValue = searchInput;
        if(newValue !== null && newValue.length > minLength) {
            window.alert(newValue);
            req = {
                method: 'SET',
                url: 'haha.php'
            };
        }
    }, 3000);   
    return function() {
        if($http !== null) {
            return $http(req);
        } else { return 0; }
    };
 });

Not sure if the return is right, as the previous return was flagging up a http null error.

So to use it I've done a few variations of the below code in my controller.

$scope.$watch('query.keyword', sendSearchData.success());

But I am having no luck and it's refusing to render. Can anyone help?

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
  • Few things of note here: I'd assume you're trying to fire off the http request after they stop typing, hence the 3 second delay. You could just implement this http://stackoverflow.com/a/22158604/771928 to then achive the same thing. You would then have a watch set up to just fire off to the service when it picks up a change after the user stops typing. In regards to your service, you should check out https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider-5f426cfe6b8c#.iicufz72n and look at the correct syntax and adjust your code accordingly. – KreepN Jul 19 '16 at 18:07
  • Thanks for the comment. I cant use a debounce as I am live searching and its stopping the searches going through instantly. – HybridHaylee Jul 20 '16 at 16:03

0 Answers0