我有一个Angular指令来处理Bootstrap弹出窗口,如下面的代码所示。在我的指令中,我将popover内容设置为HTML字符串,我认为这很难看。我想要做的是用一个"template.html“文件代替HTMLstring。这样,我就可以根据我想要显示的弹出窗口类型,对不同的模板文件使用相同的指令。不管怎样,这是我的计划。
那么,我如何以最好的方式从我的template.html加载html代码,并使用它来代替下面AngularJs指令中的HTMLstring呢?
app.directive('mypopover', function ($compile) {
var HTMLstring = "<div><label class='control-label' style='color: rgb(153, 153,153)'>Search</label> "+"<input placeholder='Search assignment' ng-model='searchText' type='text' class='form-control'> <br>"+"<label class='control-label' style='color: rgb(153, 153, 153)'>Select an assignable</label>"+"<p ng-repeat='p in projects | filter:searchText'ng-click='createEvent(user.id,date)'>"+"{{p.title}}</p></div>";
var getTemplate = function (contentType) {
var template = '';
switch (contentType) {
case 'user':
template = HTMLstring;
break;
}
return template;
}
return {
restrict: "A",
link: function (scope, element, attrs) {
var popOverContent;
if (scope.user) {
var html = getTemplate("user");
popOverContent = $compile(html)(scope);
}
var options = {
content: popOverContent,
placement: "right",
html: true,
date: scope.date
};
$(element).popover(options);
},
scope: {
user: '=',
date: '='
}
};
});发布于 2014-01-26 19:37:02
一个快速的解决方案是将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
如果需要加载外部模板,则需要使用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
发布于 2014-08-06 17:58:12
要完成Khahn的回答,如果加载动态模板,最后一部分应该如下所示:
return {
restrict: "A",
scope: {
item: "=" // what needs to be passed to the template
},
link: function(scope, element, attrs) {
getTemplate("user").then(function(popOverContent) {
var options = {
content: $compile($(popOverContent))(scope),
placement: "bottom",
html: true,
trigger: "hover"
};
$(element).popover(options);
});
}};
https://stackoverflow.com/questions/21362712
复制相似问题