Code Monkey home page Code Monkey logo

ngautocomplete's Introduction

ng-Autocomplete

A simple directive for adding google places autocomplete to a textbox element.

Updated to now use ng-model, should work much better in forms. Can now set an initial value using ng-model. Using the ng-model to set the textbox value does not trigger the autocomplete query.

Tested with angularjs-1.2.4

Uses optional directive parameters, so it won't work with <1.2. If people are interested I'll release a <1.2 version.

Examples

Usage

Include the required libraries

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>

Declare a dependency on the ngAutocomplete module

var app = angular.module('myModule', ['ngAutocomplete']);

Add the directive to a textbox

    <input type="text"  ng-autocomplete ng-model="autocomplete" options="options" details="details"/>

Documentation

  • ng-model - autocomplete textbox value

  • details - more detailed autocomplete result, includes address parts, latlng, etc. (Optional)

  • options - configuration for the autocomplete (Optional)

    • types: type, String, values can be 'geocode', 'establishment', '(regions)', or '(cities)'
    • bounds: bounds, Google maps LatLngBounds Object, biases results to bounds, but may return results outside these bounds
    • country: country String, ISO 3166-1 Alpha-2 compatible country code. examples; 'ca', 'us', 'gb'
    • watchEnter: Boolean, true; on Enter select top autocomplete result. false(default); enter ends autocomplete

example:

options = {
types: '(cities)',
country: 'ca'
}

google places autocomplete info: https://developers.google.com/maps/documentation/javascript/places

Author

Will Palahnuk (http://github.com/wpalahnuk)

Credits

google places autocomplete https://developers.google.com/maps/documentation/javascript/places

Copyright and license

The MIT License

Copyright (c) 2014 Will Palahnuk

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

ngautocomplete's People

Contributors

leovr avatar wpalahnuk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngautocomplete's Issues

Add options does not working

I am trying to get only addresses and from google docs i need to give the type of 'address', and i still get countries in the list.

 this.placeOptions = {
      types: ['address']
    }
  <input type="text" placeholder="Where do you live?"
                       ng-autocomplete="placesResult" details="profile.user.location.placesDetails"
                       options="profile.placesOptions"
                       name="location"
                       ng-model="profile.user.location.name" class="mt" required/>

Formatting the address

The value of detailsResult.formatted_address is not ok for my application, what I want to have is only street name (not country + city, as google thinks).

I'm trying to find workaround for that. So far have two options:

  1. $watch the details object and once it's changed, read address_components, format it and then re-initialize model with that.
  2. Extend ngAutocomple with format attribute, with function that takes details and returns formatted value.

I will start with first one (quick and dirty), but would be happy to have your opinion on second option, if you are fine with that, I'll pack a PR.

types not defined in getPlace()

When the watchEnter option is set to true, getPlace is used to get the location. However the types parameter is not included in the request and will therefore not return the same results as the autocomplete list.

In my example this resulted in street addresses being included in the result (I had defined types: '(cities)' in my options).

It can be fixed by adding the types parameter to the request as follows (around line 124 in ngAutocomplete):

autocompleteService.getPlacePredictions(
{
  input: result.name,
  offset: result.name.length,
  types: opts.types
},

Dropup

Hi! A stupid question here: how can I turn the dropdown into a dropup? Ideas?

There is no point in having the details attribute

If you make the ngModel point to whatever object you shove into it (ie: the object that you are currently shoving into the details attribute), then it will simplify quite a bit of your code. I struggled with your code for a few hours until I realized this. Just thought I'd point it out.

<input ng-model="foo.name" />

scope.foo = name: 'blah'

Then you never have to deal with maintaining both the ngModel and a details attribute.

Rename your (rather good) directive

Your chosen name for this project - "ngAutocomplete" - will lead most developers to believe (before reading further) that you've implemented a generic autocomplete service for use as an Angular directive.

But you haven't. You've made an autocomplete just for google places. It's very good, but would it not be better named "ngGooglePlacesAutoComplete" or similar?

Selecting address with Enter submits the form

I love the module - thanks.

I'm using it in a form to collect lots of information. There are many ways to select one of the addresses, but when the user presses the Enter key to select the address the form submits. This results in validation errors for the remaining forms.

Is there an option so that using the Enter key to select the location will not bubble up to the submitting the form?

ngAutocompelte with Bootstrap Modal

I am running into issues when you are using the autocomplete with a bootrap modal. This is more of the z-index styling for the dropdown menu of the autocomplete. As seen from the image below, you can see that with Bootstrap modal, the dropdown is behind it and selecting any values is not possible.
image

What would be the best way in modifying the code to adjust for this?

More descriptive name

ngAutocomplete sounds too generic name, as it implements only places autocompletion. I would say it should be renamed to ngAutocompletePlaces. But perhaps it is too late.

$watch for text input change

To keep track of the changes to the Places search in the input box, I am using $watch on the ng-model. In the $watch function, I am assigning the longitude and latitude as:

$scope.map.center.latitude = $scope.mapdetails.geometry['k'];
$scope.map.center.longitude = $scope.mapdetails.geometry['A'];

If I do not check on the validity of mapdetails, I get a 'undefined' error. But I realized that even if I select an item from the autocomplete list, I still see that 'mapdetails' is returned as empty. So, I am never able to retrieve the results in the $watch function.
What would be the proper way to act after an item is selected from the dropdown autocomplete list? I have tried using ng-change too, but the same result

Error: [$compile:nonassign]

I got this kind of error message when using this plugin

Error: [$compile:nonassign] http://errors.angularjs.org/1.2.23/$compile/nonassign?p0=&p1=ngAutocomplete at Error (native) at http://localhost:8888/erealestate-web/libs/angular/angular.min.js:6:450 at $get.n (http://localhost:8888/erealestate-web/libs/angular/angular.min.js:53:166) at Object.<anonymous> (http://localhost:8888/erealestate-web/libs/angular/angular.min.js:53:258) at k.$get.k.$digest (http://localhost:8888/erealestate-web/libs/angular/angular.min.js:109:268) at k.$get.k.$apply (http://localhost:8888/erealestate-web/libs/angular/angular.min.js:112:398) at h (http://localhost:8888/erealestate-web/libs/angular/angular.min.js:72:454) at v (http://localhost:8888/erealestate-web/libs/angular/angular.min.js:77:463) at XMLHttpRequest.w.onreadystatechange (http://localhost:8888/erealestate-web/libs/angular/angular.min.js:79:24)angular.min.js:92 (anonymous function)angular.min.js:68 $getangular.min.js:110 $get.k.$digestangular.min.js:112 $get.k.$applyangular.min.js:72 hangular.min.js:77 vangular.min.js:79 w.onreadystatechange

Garbage elements

Hi there, when I open a view containing the directive, it generates a div.pac-container as a :last-child into body. But when exiting, it doesn't remove it. So, when re-entering the view a few times we got:

screen shot 2015-07-06 at 20 24 16

How can I avoid this behavior, or is it the expected one?

Cannot use with tooltip

Tooltip and ngAutocomplete cannot be used together. It would be very handy if you could.

I've made a plunker to illustrate: http://plnkr.co/edit/LW4bJ1aD2iZF4IAsAFFT?p=preview

Uncomment the last div to illustrate the breakage. Here's what you get...

Error: [$compile:multidir] Multiple directives [ngAutocomplete, tooltip] asking for new/isolated scope on: <input type="text" name="withBoth" ng-autocomplete="" ng-model="withBoth" tooltip="This field is required" tooltip-trigger="{{{true:'blur',false:'never'}[myForm.withBoth.$error.required]}}" class="form-control" id="textToAddress" placeholder="Ship To" required="">

Plunkr broken

How are you going to have errors in the "Simple Usage" examples Plunkr...

Add to Bower

Can please you tag a release and add to this library to Bower?

position issue when used on dialog

Drawer location for selecting the place is misplaced (it's coming on background screen rather on dialog) when used this directive on dialog.

image

ngAutocomplete resets binded value

I have a city search with ng-autocomplete. When i want to edit my details it resets the city value on the scope to an empty string instead of taking the existing value.

any thoughts?

getLng() / getLng()

Hi,

thanks for your great angular integration. I would like to tell you and other people (maybe you should put this into your documentation) that the scope-var details will provide lat and long inside of "geometry" ($scope.details.geometry.location)

You can get latitude trough key "j" and longitude on key "C". This vars seems to change from time to time to J and K, which lead into bugs. After reading some documentation, I've figured out the bulletproof method for getting the lat and lng.

$scope.details.geometry.location.lat()
$scope.details.geometry.location.lng()

I'm sure that unexperienced users will make the same mistake and try to access the keys directly, which is a bad idea. It would be great if you could mention the methods above to prevent errors.

Force language of returned address

Is it possible to force language google-places should use to return addresses?
I mean: I need all street addresses to be formatted in the same language (for example, "Street ABC, Italy", and not "Strada ABC, Italia"), indipendently by client's browser language...
I see in ngAutocomplete there is a "country" option, but I am not sure I understand it's meaning; but for sure it doesn't fulfill my need... :-(

Text value not correct after selection

I think after selecting a location the element value should be equal to formatted_address value.

e.g For the location term cali
the field value is set to "Cali - Valle del Cauca Department, Colombia"
but it should be "Cali, Cali, Valle del Cauca, Colombia"

Solution for autocomplete model not updating when pressing enter

I would type some characters into the autocomplete text field such as 'ap', then I would use my arrow keys to navigate to one of the autocompleted options. Then, I would hit enter which would submit the form. However, when I press enter, the ng-model still only had a value of 'ap' instead of 'appliance store' (or whatever starts with 'ap').

So, in order to solve that, I added the following code at line 83 of your directive. I think that a lot of people would be looking for a fix like this.

// Custom code to make autocomplete field pass autocomplete value to the model when enter is pressed
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function () {
controller.$setViewValue(element.val());
});
}
});
// end of custom code

Add ability to filter the data put into details.

I transform the data that comes back from the places service. Could be done in this directive or could be done in my code. Not sure... feel free to close if you don't think this is beneficial.

Add 'lodging' as a place type

Thanks for this library. Is it possible to support 'lodging' as a place type by itself?

When I set the types parameter to 'lodging', it does not work. Only accepts four strings: 'geocode', 'establishment', '(regions)', or '(cities)'.

Facing problem while testing it.

I am writing Unit test for this directive. I am really confused how to fire place_changed event, and then get the details param from this directive. Can some one guide me?

display only countries.

I would like to display only countries in the dropdown, but I can't find the option in the parameter.
How can i do that?
I also can't find the code place to filter the result.

Cant evaluate dynamic option value

I am trying to input a dynamic value to the options parameter but it does not seem to be evaluating. What would be the best way to do this? I have an ng-repeat form that I will not be able to have a scoped variable for each ngAutocomplete input. An example:

http://plnkr.co/edit/41hfxvlZABIGeGAikfi2?p=preview

As you can see I have two ngAutocomplete inputs both have the country as a dynamic option but neither work. Is there a way to do this?

One thing I have tried was changing options: "=?" to options: "@?" in the directive which seems to allow {{country}} but it still does not limit the countries correctly.

npm install?

Any reason why this module is not a published npm package?

Not mobile friendly

I am making an app using your amazing directive. Unfortunetly, it does not click properly when I integrate it with my app. I am using the ionic framework. Here is a sample(use on your phone) . http://shielded-hamlet-4180.herokuapp.com . Please let me know if you plan to support mobile.

Autocomplete results on top

Hi everyone!
I'm trying to introduce this module into an hybrid app and I was wondering if I could turn the autocomplete dropdown into a dropup. Is it possible?

Thank you in advance for you help! :)

problem with ' (apostroph)

Hi,

when google places return a name with ' inside, the details scope won't update and the model value is wrong?

Error loading

When adding ngAutocomplete to a controller I keep getting this error:

Unknown provider: ngAutocompleteProvider <- ngAutocomplete

While using 2 input boxes, second box's details.geometry shows undefined

Hi,

I am not sure whether I am doing this right. But I get an error saying that the details variable for workDetails is undefined

In HTML,

I have Home Location input box with ng-autocomplete ng-model="homeAddress" details="homeDetails" and Work Location input box with ng-autocomplete ng-model="workAddress" details="workDetails"

JavaScript
$scope.$watch('[workAddress, homeAddress]', function(newValue, oldValue) {
if(newValue[1] && newValue[0]) {
console.log($scope.workDetails.geometry.location.lat());
}
}, true);

I get 'Error: $scope.workDetails.geometry is undefined' in my console as soon as I enter values for my work location

Same thing happens for homeDetails if Home Location is placed after Work Location.

What am I doing wrong?

Blank value when place is not found

I was testing the plunker simple example and I found when I typed 'ssdfssd' or another value out of the allowed values, the value was stored in scope anyway and I didn't need it. So, I fixed this validating 'geometry' position:

google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
scope.$apply(function() {
scope.details = scope.gPlace.getPlace();
if (!scope.details.geometry) {
scope.ngAutocomplete = '';
}
else
scope.ngAutocomplete = element.val();
//scope.ngAutocomplete = JSON.stringify(scope.details);
});
})

is it a good way to fix it or what do you suggest instead of it?

Thanks in advance and excuses for my bad english :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.