0

I have several inputs which bind to different model fields, like model.a and model.b, and I need to send request for the server to get auto-complete data. So the logic for both are the same. I want to add ng-change="changeHandler()" directive to each. But inside changeHandler() I need to get input value - how to do that properly? I can't just take some model field because I have the same code for both fields.

3 Answers 3

2

If you want to do this without firing off a GET to a web API on every change, you'll have to get a bit more sophisticated.

Set up a $watch on model.a or model.b (or both)

In the $watch handler, pull autocomplete results via a Promise, which will look a bit like this:

myModule.factory('HelloWorld', function($q, $timeout) {

  var getMessages = function() {
    var deferred = $q.defer();

    $timeout(function() {
      deferred.resolve(['Hello', 'world!']);
    }, 2000);

    return deferred.promise;
  };

  return {
    getMessages: getMessages
  };

});

// from: http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

Then bind the autocomplete to the results of the Promise.

You'll also want to debounce your changes, this SO post may help: How to write a debounce service in AngularJS

I think this blog post may help: http://www.grobmeier.de/angular-js-autocomplete-and-enabling-a-form-with-watch-and-blur-19112012.html#.UkMBIB1Dsak

Sign up to request clarification or add additional context in comments.

Comments

1

Pass the model name into the change function as a parameter:

<input type='text' ng-model='testinput' ng-change='changeHandler(testinput)'/>

Comments

1

You can wrap this all up in a directive which will have access to scope.model.a or you can just do it like this:

ng-change="chanageHandler(model.a)" ng-model="model.a"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.