Search code examples
angularjsangularjs-directiveangular-ui-bootstrapangularjs-factoryangular-ui-typeahead

Angular-ui Typeahead directive calling factory


I'm trying to use a factory within the directive's controller, but it doesnt populate the typeahead as it should. By using $http.get directly inside the directive, it works perfectly.

Typeahead html

<input type="text" ng-model="asyncSelected" placeholder="Locations loaded via $http" uib-typeahead="address for address in getLocation($viewValue)" typeahead-loading="loadingLocations" typeahead-no-results="noResults" class="form-control" autocomplete>
<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>
<div ng-show="noResults">
<i class="glyphicon glyphicon-remove"></i> No Results Found
</div>

Directive

'use strict';

angular.module('myModule')
    .directive('autocomplete', function() {
        return {
            templateUrl: 'app/autocomplete/autocomplete.html',
            restrict: 'EA',
            link: function(scope, element, attrs) {},
            controller: function($scope, autocompleteFactory, $http) {
                $scope.getLocation = function(val) {                    autocompleteFactory.getCities('//maps.googleapis.com/maps/api/geocode/json', val).then(function(response) {
                        return response.data.results.map(function(item) {
                            return item.formatted_address;
                        });
                    });
                };

            // return $http.get('//maps.googleapis.com/maps/api/geocode/json', {
            //  params: {
            //      address: val,
            //      sensor: false
            //  }
            // }).then(function(response) {
            //  return response.data.results.map(function(item) {
            //      console.log(item.formatted_address);
            //      return item.formatted_address;
            //  });
            // });

            //};
            //}

        }
    }
});

Factory

'use strict';

angular.module('myModule')
  .factory('autocompleteFactory', function($http, $q) {
    return {
      getCities: function(url, val) {
        return $http({
          url: url,
          method: "GET",
          params: {
            address: val,
            sensor: false
          }
        });
      }
    }
  });

working fiddle

not working fiddle

Any clues? Thanks !


Solution

  • You have to return the cities on line 24: http://jsfiddle.net/ngzxL60h/2/