2

I have an angular application where I use the routeprovider which points to different templates. A list template and a map template. These templates have controllers associated to them. The problem is when i change the route, then the current controller instance is destroyed, and a new controller instance for the current template is re-initated. This is a problem because the map template initiates an openlayers map which is quite browser heavy.

Routeprovider:

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.            
        when('/list', {
            reloadOnSearch: false,
            templateUrl: '/listTpl.html'
        }).
        when('/map/', {
            reloadOnSearch: false,
            templateUrl: '/mapTpl.html'
        })
        .otherwise({
            redirectTo: '/list'
        });  
    });
}]);

MapTpl.html

script type="text/ng-template" id="/mapTpl.html">
<div ng-controller="mapController" class="map">
    html stuff
</div>

So are there any way to persist these controllers, so the routeprovider just switches between those instances?

Thank you!

Farsen
  • 1,387
  • 3
  • 21
  • 48
  • Why aren't you using the `controller` property of your route configuration? I really don't think `ng-controller` belongs in an application with routing – Phil Sep 27 '16 at 07:02
  • 1
    there are 2 ways: have a parent state that hosts the controller, while your routes will be child states that dont have controllers of their own; or create a service that hosts shared objects. – Vladimir M Sep 27 '16 at 07:03
  • 1
    @VladimirM I don't think `ngRoute` supports the idea of child routes. `ui.router` on the other hand does – Phil Sep 27 '16 at 07:06
  • Thanks alot for your comments! @Phil I´ve looked into your suggestion and found this great and simple example: http://www.w3schools.com/angular/tryit.asp?filename=try_ng_routing_controller - problem is that it doesent keep the state/scope. – Farsen Sep 28 '16 at 06:27
  • @Vladimir I´m quite new to angular, could you please explain suggestion #1 in detail? And as far as I can see, ui-router doesent seem to solve the problem? A detail that might be important is, that in my "html stuff" I have a custom map directive, which is the one I would like to keep alive. – Farsen Sep 28 '16 at 06:27
  • 2
    @Farsen as Phil has commented, ngRoute does not seem support child states. In my applications I use [ui.router](https://github.com/angular-ui/ui-router) which provides more functionality, including child states. You may check this thread for more informatuion on differences. http://stackoverflow.com/questions/21023763/angularjs-difference-between-angular-route-and-angular-ui-router . – Vladimir M Sep 28 '16 at 06:37

0 Answers0