一个快速的解决方案是使用 templateCache 和内联模板:
内联模板:
<script type="text/ng-template" id="templateId.html">
This is the content of the template
</script>
Js:
app.directive('mypopover', function ($compile,$templateCache) {
var getTemplate = function (contentType) {
var template = '';
switch (contentType) {
case 'user':
template = $templateCache.get("templateId.html");
break;
}
return template;
}
DEMO http://plnkr.co/edit/qoTcdEAA5o0PgQ7IwJLb?p=preview
如果需要加载外部模板,则需要使用ajax $http手动加载模板并放入缓存中。然后你可以使用$templateCache.get
以便稍后检索。
$templateCache.put('templateId.html', YouContentLoadedUsingHttp);
示例代码:
var getTemplate = function(contentType) {
var def = $q.defer();
var template = '';
switch (contentType) {
case 'user':
template = $templateCache.get("templateId.html");
if (typeof template === "undefined") {
$http.get("templateId.html")
.success(function(data) {
$templateCache.put("templateId.html", data);
def.resolve(data);
});
} else {
def.resolve(template);
}
break;
}
return def.promise;
}
DEMO http://plnkr.co/edit/WljWO6RVGIWRTvCN8KO9?p=preview