Angular-ui Typeahead指令调用工厂

时间:2015-12-28 20:30:39

标签: angularjs angularjs-directive angular-ui-bootstrap angularjs-factory angular-ui-typeahead

我正在尝试在指令的控制器中使用工厂,但它不会填充应该的类型。通过在指令中直接使用$ http.get,它可以很好地工作。

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>

指令

'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;
            //  });
            // });

            //};
            //}

        }
    }
});

'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

任何线索? 谢谢!

1 个答案:

答案 0 :(得分:1)

您必须return第24行的城市:http://jsfiddle.net/ngzxL60h/2/