How to avoid memory leaks using Javascript google.maps.places.Autocomplete in Angular ng-view

522 views Asked by At

I'm having trouble with google.maps.places.Autocomplete and single page app. Long story short I have a Angular directive with form with input field in it. The input field has autocomplete functionality so when clicked and address typed it shows matching addresses. Its single page app so whe user navigates to the page it loads appropriate ng-view. When user navigates away to another page and another content is loaded in ng-view memory is not cleared. Using profile and snapshots in Google Chrome I clearly see there is rubbish left over and the form element is detached (its marked in red). This is due to input field where autocomplete is attached. I narrowed it down to the line where new google.maps.places.Autocomplete is declared. If I remove the call to autocomplete memory clears as it should, otherwise however the entire form where input aaa exists stays in memory. I also clear all the variables on $destroy so it could be garbage collected but nothing seems to work. Is there any solution to this and any way to use Autocomplete in dynamically loaded ng-views without leaking memory?

link: function (scope, elem, attrs, ctrl) {
                var autocomplete;
var aaa=document.getElementById('address');

                function initializeGoogleMaps() {
                    autocomplete = new google.maps.places.Autocomplete(
                        (aaa), {
                            types: ['geocode']
                        });
                    scope.$on('$destroy', function () {
                        $(".pac-container").remove();
                        autocomplete=null;
                    });



    }

        initializeGoogleMaps();
// some other code
0

There are 0 answers