silent_coder
silent_coder

Reputation: 6512

angularjs bind the same listener to different inputs, how to get input value

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.

Upvotes: 0

Views: 783

Answers (3)

jcollum
jcollum

Reputation: 46589

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

Upvotes: 2

Jonathan Rowny
Jonathan Rowny

Reputation: 7588

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"

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

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

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

Upvotes: 1

Related Questions