ng-template 到 src 的变量
ng-template to Variable from src
我想将模板的内容加载到一个变量中。目前我的代码看起来像这样。
HTML
<script type="text/ng-template" id="a.html" src="templates/a.html"></script>
JS
vm.template = $templateCache.get('a.html');
console.log("Template: " + vm.template);
这应该将 'templates/a.html' 的内容加载到 vm.template 中。遗憾的是,这不起作用。变量 vm.template 不包含模板。
我在测试时发现,如果我将模板的内容直接写到脚本标签中,就像这样
<script type="text/ng-template" id="a.html">Hello!</script>
它确实有效。
在 ng-template 上使用 src 可能不起作用:
您可以使用 ng-include:
<script type="text/ng-template" id="a.html">
<div ng-include="'templates/a.html'"></div>
</script>
或者在您的路由配置中执行此操作:
.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: 'templates/a.html',
controller: 'aController'
}).when("/second", {
templateUrl: 'templates/b.html',
controller: 'bController'
}).otherwise({redirectTo: "/"});
});
此外,它们会向您的服务器发出 /templates/a.html
GET 请求(确保您已配置静态信息)
您可以使用指令:
.directive('script', function() {
return {
restrict:'E',
scope: false,
controller: function($attrs, $templateCache, $http, $log) {
if($attrs['type'] != "text/ng-template" || !$attrs['src']){
return;
}
var id = $attrs['id'] || $attrs['src'];
var src = $attrs['src'];
$log.debug('Loading %s template from %s', id, src);
$http.get(src).then(function(response){
$log.debug('Loaded template %s', id);
$templateCache.put(id, response.data);
});
}
};
})
我想将模板的内容加载到一个变量中。目前我的代码看起来像这样。
HTML
<script type="text/ng-template" id="a.html" src="templates/a.html"></script>
JS
vm.template = $templateCache.get('a.html');
console.log("Template: " + vm.template);
这应该将 'templates/a.html' 的内容加载到 vm.template 中。遗憾的是,这不起作用。变量 vm.template 不包含模板。
我在测试时发现,如果我将模板的内容直接写到脚本标签中,就像这样
<script type="text/ng-template" id="a.html">Hello!</script>
它确实有效。
在 ng-template 上使用 src 可能不起作用:
您可以使用 ng-include:
<script type="text/ng-template" id="a.html">
<div ng-include="'templates/a.html'"></div>
</script>
或者在您的路由配置中执行此操作:
.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: 'templates/a.html',
controller: 'aController'
}).when("/second", {
templateUrl: 'templates/b.html',
controller: 'bController'
}).otherwise({redirectTo: "/"});
});
此外,它们会向您的服务器发出 /templates/a.html
GET 请求(确保您已配置静态信息)
您可以使用指令:
.directive('script', function() {
return {
restrict:'E',
scope: false,
controller: function($attrs, $templateCache, $http, $log) {
if($attrs['type'] != "text/ng-template" || !$attrs['src']){
return;
}
var id = $attrs['id'] || $attrs['src'];
var src = $attrs['src'];
$log.debug('Loading %s template from %s', id, src);
$http.get(src).then(function(response){
$log.debug('Loaded template %s', id);
$templateCache.put(id, response.data);
});
}
};
})