and*_*rsh 43 offline angularjs angularjs-routing
加载Angular应用程序后,我需要一些离线可用的模板.
这样的事情是理想的:
$routeProvider
.when('/p1', {
controller: controller1,
templateUrl: 'Template1.html',
preload: true
})
Run Code Online (Sandbox Code Playgroud)
and*_*rsh 54
这是@gargc对答案的补充.
如果您不想使用脚本标记指定模板,并且想要从文件加载模板,则可以执行以下操作:
myApp.run(function ($templateCache, $http) {
$http.get('Template1.html', { cache: $templateCache });
});
myApp.config(function ($locationProvider, $routeProvider) {
$routeProvider.when('/p1', { templateUrl: 'Template1.html' })
});
Run Code Online (Sandbox Code Playgroud)
gar*_*rst 43
有一个模板缓存服务:$ templateCache,可用于在javascript模块中预加载模板.
例如,取自文档:
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
Run Code Online (Sandbox Code Playgroud)
从html文件预生成javascript模块甚至还有一项艰巨的任务:grunt-angular-templates
另一种可能不太灵活的方法是使用内联模板,例如,在index.html中使用这样的脚本标记:
<script type="text/ng-template" id="templates/Template1.html">template content</script>
Run Code Online (Sandbox Code Playgroud)
表示模板可以稍后以与路由配置中的真实URL相同的方式进行寻址(templateUrl: 'templates/Template1.html')
Tho*_*eck 27
基于Raman Savitski的方法,我认为我对这个问题有一个稍微改进的解决方案,但它有选择地加载模板.它实际上允许这样要求的原始语法:
$routeProvider.when('/p1', { controller: controller1, templateUrl: 'Template1.html', preload: true })
这允许您只是装饰您的路线,而不必担心在其他地方更新另一个预加载配置.
这是在开始时运行的代码:
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 });
}
}
}
})
]);
Run Code Online (Sandbox Code Playgroud)
Ram*_*ski 18
预加载模块路由中定义的所有模板.
angular.module('MyApp', [])
.run(function ($templateCache, $route, $http) {
var url;
for(var i in $route.routes)
{
if (url = $route.routes[i].templateUrl)
{
$http.get(url, {cache: $templateCache});
}
}
})
Run Code Online (Sandbox Code Playgroud)