(function(angular) { var app = angular.module('batmanDelivers'); app.directive("addressSearch", addressSearch); addressSearch.$inject = ['$parse', '$rootScope', '$http', '$timeout', '$sce'] function addressSearch($parse, $rootScope, $http, $timeout, $sce) { return { templateUrl: '/src/js/directives/address-search/partial.html', replace: true, //study transclude: true, //study link: function(scope, elm, attrs) { scope.placeholder = attrs["placeholder"]; scope.address = { AddressLine1: null, AddressLine2: null, City: null, PostCode: null, Latitude: null, Longitude: null, Description: null } scope.$watch('address.Description', function(value) { scope.show = true; //learn debounce if (value && value.length > 3) { scope.searching = true; $http({ method: "GET", url: "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + value + "&key=AIzaSyAPYatPrCcmNcVdAO_MF0YhO3c1mgdLvuQ" }).then(function mySuccess(response) { scope.searching = false; scope.addresses = response.data.predictions; }, function myError(response) { scope.searching = false; scope.error = response.statusText; }); } }); scope.selectAddress = function(place) { $http({ method: "GET", url: "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place.place_id + "&fields=geometry,adr_address,address_component,formatted_address&key=AIzaSyAPYatPrCcmNcVdAO_MF0YhO3c1mgdLvuQ" }).then(function mySuccess(response) { scope.show = false; scope.res = response.data.result; scope.address = { AddressLine1: result.address_components[1].long_name, AddressLine2: result.address_components[2].long_name, City: result.address_components[3].long_name, PostCode: result.address_components[0].long_name, Latitude: result.geometry.location.lat, Longitude: result.geometry.location.lng, Description: place.description } scope.googleSearch = place.description; }, function myError(response) { scope.error = response.statusText; }); } scope.blur = function() { setTimeout(function() { scope.show = false; }, 500) } } } } })(angular);