forked from DmitryEfimenko/ngAutocomplete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathngAutocomplete.js
194 lines (178 loc) · 9 KB
/
ngAutocomplete.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
'use strict';
/**
* Source: https://github.com/DmitryEfimenko/ngAutocomplete
* A directive for adding google places autocomplete to a text box
* google places autocomplete info: https://developers.google.com/maps/documentation/javascript/places
*
* Full Example:
* <input type="text" ng-model="details.formattedAddress" ng-autocomplete details="details" options="options" validate-fn="customValidate()" />
*
* creates the autocomplete text box
*
* Required attributes
* [ng-autocomplete]: Specifies the directive
* [ng-model]: Set initial value for the textbox
* [details]: Specifies result object which is a bit flattened "google place" object, where properties will be set to the address types.
* For more info about google types, see: https://developers.google.com/maps/documentation/geocoding/#Types
*
* Optional attributes
* [options]: Options provided by the user that filter the autocomplete results
*
* options = {
* types: type, string, values can be 'geocode', 'establishment', '(regions)', or '(cities)'
* bounds: bounds, google maps LatLngBounds Object
* country: country string, ISO 3166-1 Alpha-2 compatible country code. examples; 'ca', 'us', 'gb'
* }
*
* [validate-fn]: allows to add any custom validation logic to run upon an address is selected from the list of suggestions
*
* IMPORTANT!
* You must declare $scope.details = {}; in the controller
*/
angular.module("ngAutocomplete", [])
.directive('ngAutocomplete', ['$parse',
function ($parse) {
function convertPlaceToFriendlyObject(place) {
var componentForm = {
street_number: 'short_name',
route: 'short_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
var result = undefined;
if (place) {
result = {};
for (var i = 0, l = place.address_components.length; i < l; i++) {
var type = place.address_components[i].types[0];
if (i == 0) {
result.searchedBy = type;
}
result[type] = place.address_components[i][componentForm[type]];
}
result.formattedAddress = place.formatted_address;
result.lat = place.geometry.location.lat();
result.lng = place.geometry.location.lng();
}
return result;
}
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, $element, $attrs, $ctrl) {
if (!angular.isDefined($attrs.details)) {
throw '<ng-autocomplete> must have attribute [details] assigned to store full address object';
}
var getDetails = $parse($attrs.details);
var setDetails = getDetails.assign;
var getOptions = $parse($attrs.options);
var googleServiceTested = false;
var googleServiceWorks = false;
//options for autocomplete
var opts;
//convert options provided to opts
var initOpts = function () {
opts = {};
if (angular.isDefined($attrs.options)) {
var options = getOptions($scope);
if (options.types) {
opts.types = [];
opts.types.push(options.types);
}
if (options.bounds) {
opts.bounds = options.bounds;
}
if (options.country) {
opts.componentRestrictions = {
country: options.country
};
}
}
};
var testGoogleService = function(cb) {
if (!googleServiceTested) {
var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({ input: 'Phoenix' }, function (predictions, status) {
googleServiceTested = true;
googleServiceWorks = status == google.maps.places.PlacesServiceStatus.OK;
cb();
});
} else {
cb();
}
}
//create new autocomplete
//reinitializes on every change of the options provided
var newAutocomplete = function () {
testGoogleService(function () {
if (googleServiceWorks) {
var gPlace = new google.maps.places.Autocomplete($element[0], opts);
google.maps.event.addListener(gPlace, 'place_changed', function() {
$scope.$apply(function() {
var place = gPlace.getPlace();
var details = convertPlaceToFriendlyObject(place);
setDetails($scope, details);
$ctrl.$setViewValue(details.formattedAddress);
$ctrl.$validate();
});
if ($ctrl.$valid && angular.isDefined($attrs.validateFn)) {
$scope.$apply(function() {
$scope.$eval($attrs.validateFn);
});
}
});
}
});
};
newAutocomplete();
$ctrl.$validators.parse = function (value) {
if (googleServiceWorks) {
var details = getDetails($scope);
var valid = ($attrs.required == true && details != undefined && details.lat != undefined) ||
(!$attrs.required && (details == undefined || details.lat == undefined) && $element.val() != '');
return valid;
} else {
return true;
}
};
$element.on('keypress', function (e) {
// prevent form submission on pressing Enter as there could be more inputs to fill out
if (e.which == 13) {
e.preventDefault();
}
});
//watch options provided to directive
if (angular.isDefined($attrs.options)) {
$scope.$watch($attrs.options, function () {
initOpts();
newAutocomplete();
});
}
// user typed something in the input - means an intention to change address, which is why
// we need to null out all fields for fresh validation
$element.on('keyup', function (e) {
if (googleServiceWorks) {
// chars 0-9, a-z numpad 0-9 backspace delete space
if ((e.which >= 48 && e.which <= 90) || (e.which >= 96 && e.which <= 105) || e.which == 8 || e.which == 46 || e.which == 32) {
var details = getDetails($scope);
if (details != undefined) {
for (var property in details) {
if (details.hasOwnProperty(property) && property != 'formattedAddress') {
delete details[property];
}
}
setDetails($scope, details);
}
if ($ctrl.$valid) {
$scope.$apply(function() {
$ctrl.$setValidity('parse', false);
});
}
}
}
});
}
};
}
]);