Mor*_*yae 10 angularjs angular-ui-router
我可以在ui-router的模板中使用$ templateCache吗?
模板将缓存在resolve部分中,我想在同一状态下使用缓存模板.
$stateProvider
.state('dashboard', {
url: "/dashboard",
template: function($templateCache){
console.log('test 2');
return $templateCache.get('templates/template1.html'); // returns undefined
},
resolve:{
baseTemplates: function($ocLazyLoad) {
// here the template will be cached...
return $ocLazyLoad.loadTemplateFile(['base/dashboard.html']).then(function(){
console.log('test 1');
});
}
}
})
// console prints "test 2" before than "test 1"
Run Code Online (Sandbox Code Playgroud)
更新:(+代码更新)
我认为我的代码的解决部分存在问题.因为它在模板部分之后运行!并导致返回$ templateCache.get未定义.
我使用ocLazyLoad插件来缓存模板,它返回一个正确的promise.
为什么模板不等待解决?
Rad*_*ler 19
如何动态设置动态模板的方式不是通过template属性而是templateProvider.有一个工作的plunker,这是片段:
// this is a run event (executed after config in fact)
// in which we do inejct a value into $templateCache
.run(function($templateCache){
// this could be lazy... elswhere
$templateCache.put('templates/template1.html'
, '<div><h4>dashboard</h4></div>');
})
.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/dashboard');
$stateProvider.state('dashboard', {
url: '/dashboard',
// this is the place where to resolve dynamic template
templateProvider: function($templateCache){
// simplified, expecting that the cache is filled
// there should be some checking... and async $http loading if not found
return $templateCache.get('templates/template1.html');
},
})
});
Run Code Online (Sandbox Code Playgroud)
看到:
而且,我想说,不是你自己可以使用它$templateCache,但它已经被使用了ui-router.负责为我们的视图加载模板(来自url,string ...)的主要服务是:
正如其代码所示,它确实$templateCache用作自然优化($templateFactory 代码片段 :)
...
/**
* @ngdoc function
* @name ui.router.util.$templateFactory#fromUrl
* @methodOf ui.router.util.$templateFactory
*
* @description
* Loads a template from the a URL via `$http` and `$templateCache`.
*
* @param {string|Function} url url of the template to load, or a function
* that returns a url.
* @param {Object} params Parameters to pass to the url function.
* @return {string|Promise.<string>} The template html as a string, or a promise
* for that string.
*/
this.fromUrl = function (url, params) {
if (isFunction(url)) url = url(params);
if (url == null) return null;
else return $http
.get(url, { cache: $templateCache })
.then(function(response) { return response.data; });
};
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17852 次 |
| 最近记录: |