Reuse an AngularJS template between page views for

2019-05-23 04:56发布

问题:

I am using a third party JS API that creates an object attached to an html element on my angular template.

Each time the template is loaded I want to reuse the object already created and reattach it to the correct html element.

In this plunker you can see the issue demonstrated. And here are the steps to reproduce. I really appreciate any suggests on how to preserve the first object between page loads.

Thanks in advance.

Problem Description

To understand the problem:

  • Tap the "Show Map" link above. The "map.html" template is loaded correctly and a map is shown.
  • Move the map or zoom in a little so the map is changed
  • On the Map page tap "Show Home Page" link to return to this page.
  • Now, tap the home page link to return to this page
  • Now, tap "Show Map" for a second time and you can see the map is recreated.

I would like for the "map.html" template to reuse the existing map object so the map stays unchanged between page views.

回答1:

This is a non-trivial problem.

The angular-gm module reuses map instances so there is no memory leak. There is also angular-google-maps.



回答2:

I do it with the help of the routeproviderapi

http://docs.angularjs.org/api/ng.$routeProvider

You have the opportunity to have a resolver, that resolves all dependencies, that your controller needs for rendering the template. My resolover caches the object for the specific routeparams and will return this already instantiated object.

So basically your map-object is a dependency of your controller. The resolver manages the injection of this dependency and there you can implement some caching.