Is there a way to preload templates when using AngularJS routing?

前端 未结 5 1627
渐次进展
渐次进展 2020-12-04 11:23

After the Angular app is loaded I need some of the templates to be available offline.

Something like this would be ideal:

$routeProvider
  .when(\'/p         


        
5条回答
  •  伪装坚强ぢ
    2020-12-04 11:49

    I think I have a slightly improved solution to this problem based on Raman Savitski's approach, but it loads the templates selectively. It actually allows for the original syntax that was asked for like this:

    $routeProvider.when('/p1', { controller: controller1, templateUrl: 'Template1.html', preload: true })

    This allows you to just decorate your route and not have to worry about updating another preloading configuration somewhere else.

    Here is the code that runs on start:

    angular.module('MyApp', []).run([
        '$route', '$templateCache', '$http', (function ($route, $templateCache, $http) {
            var url;
            for (var i in $route.routes) {
                if ($route.routes[i].preload) {
                    if (url = $route.routes[i].templateUrl) {
                        $http.get(url, { cache: $templateCache });
                    }
                }
            }
        })
    ]);
    

提交回复
热议问题