AngularJS with Google Geocode Validation
Create the Example Form
A simple form is made to test the validation and service. This form has only one input and a submit box. The input will have its value validated to be a real location. The submit box is disabled until the form is valid.
Creating an AngularJS Validation Directive
Now lets create the validation directive. When I started this task I followed the
custom validation example at the AngularJS website. The function
in the geocode service returns a promise. In order to understand
promises I read
the article “Promises Explained as a Cartoon.”
To act on a promise you add code to a function called by
Make sure that if you use camel case to define your directive you don’t use camel case in your HTML form. As you can see above I have “valid-location”, while my directive is “validLocation.” Note they use “unshift” on the $parsers, while I use “push.” This is to just add it to the list of parsers and leave it up to your ordering in the HTML to dictate priority. “Unshift,” would always put it at the top.
Creating the Geocode AngularJS Service
In this part we will be creating an adapter for the Google Geocode service that
returns a promise. Geocoding is the process of looking up latitude and longitude
from a string. The Google Geocoding API requires a general location to begin its
search. In this example the variable
myLatLng is that location. To create a promise
follow this easy pattern:
- Create the deferred.
- Call the asynchronous function/long running function. It MUST return deferred.resole and/or deferred.reject.
- Return the deferred promise.
You can see this pattern being followed in this service.