Ответ 1
Способ динамического задания динамического шаблона не выполняется с помощью свойства 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');
},
})
});
См:
А также, я бы сказал, что не у вас может использовать $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; });
};
...