0
votes

So i'm doing some basic typeahead code here: http://codepen.io/anon/pen/xwZaLN

I just want to pass in the input value into a parameter for an async http call based on the typeahead. That way the values the typeahead uses are loading in asynchronously.

Here is my input:

<input typeahead="ref as ref.display_value for ref in getLocationData('location') | filter:$viewValue | limitTo:8" ng-model="location" ng-model-options="{ debounce: 500 }" />

Here is my code:

var app = angular.module('test', ['ui.bootstrap']);
(function() {
  //another comment...
  angular
    .module('test')
    .controller('testing', ['$scope', '$rootScope', function($scope, $rootScope) {

      $scope.location = 'Type a Location';

      $scope.getLocationData = function(field) {
        console.log('SCOPE VALUE IS: ', $scope[field]);
        var params = {
          'query': $scope[field]
        };
        //go get HTTP stuff here....eventually.

      };
    }]);

For some reason the scope property associated with the typeahead function is always one digest cycle behind.

If you open your console in that codepen and start changing the field value you'll see the console log always outputs what the previous input value was and not the current scope property. I have the scope binded to a text output to show it's updating in real time.

If you change the function from being called in the typeahead to an ng-change it works just fine. So I know it's the typeahead, but not sure why it's behind or what I need to change to make it work.

Am I doing this incorrectly? Any ideas why this code is being weird?

1

1 Answers

1
votes

The getLocationData function is called before the scope property is updated. You may want to change your input to the below (notice the $viewValue being passed as a parameter to getLocationData):

<input typeahead="ref as ref.display_value for ref in getLocationData('location', $viewValue) | filter:$viewValue | limitTo:8" ng-model="location" ng-model-options="{ debounce: 500 }" />

And then use the following within Javascript (notice the new val parameter):

$scope.getLocationData = function(field, val) {
    console.log('SCOPE VALUE IS: ', $scope[field]);
    console.log('TYPED IN VALUE IS: ', val);