如何缓存angularjs partials?
发布时间:2020-12-17 17:19:58 所属栏目:安全 来源:网络整理
导读:在 angularjs生产中缓存部分的最简单/最现代的方法是什么? 目前代码如下: $routeProvider.when('/error',{templateUrl: 'partials/error.html',controller: 'ErrorCtrl'}); 其中templateUrl显然是指向单独文件的http路径.在移动设备上,该文件的加载时间是
在
angularjs生产中缓存部分的最简单/最现代的方法是什么?
目前代码如下: $routeProvider.when('/error',{templateUrl: 'partials/error.html',controller: 'ErrorCtrl'}); 其中templateUrl显然是指向单独文件的http路径.在移动设备上,该文件的加载时间是显而易见的,我很乐意只缓存所有内容. 解决方法
答案的主要部分是
$templateCache.摘录:
var myApp = angular.module('myApp',[]); myApp.run(function($templateCache) { $templateCache.put('templateId.html','This is the content of the template'); }); 任何html模板都可以移动到$templateCache,我们的应用程序的其余部分将按预期运行(无需其他更改) 本地存储作为缓存 如果我们希望将模板保留在客户端上,我们也可以使用本地存储.这个angular-local-storage扩展将简化很多东西. 所以,让我们将run()调整为 >如果我们在客户端上还没有模板,请观察本地存储 调整后的代码 .run([ 'localStorageService','$templateCache','$http',function myAppConfig(localStorageService,$templateCache,$http) { // The clearAll() should be called if we need clear the local storage // the best is by checking the previously stored value,e.g. version constant // localStorageService.clearAll(); var templateKey = "TheRealPathToTheTemplate.tpl.html"; // is it already loaded? var template = localStorageService.get(templateKey); // load the template and cache it if (!template) { $http.get(templateKey) .then(function(response) { // template loaded from the server template = response.data; localStorageService.add(templateKey,template); $templateCache.put(templateKey,template); }); } else { // inject the template $templateCache.put(templateKey,template); } }]) 所以,通过这种方式,我们可以从本地存储中获利.它充满了来自服务器的“模板”,保存在那里……因此下次不会加载. 注意:非常重要的是注入一些版本密钥/值并检查它.如果本地存储已过时…必须重新加载所有模板. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |