Файл Html как содержимое в Bootstrap popover в директиве AngularJS
У меня есть директива Angular для обработки всплывающих подсказок Bootstrap, как показано в приведенном ниже коде. В моей директиве я устанавливаю содержимое popover в HTML-строку, которая, я думаю, уродлива.
Я хочу сделать, это использовать файл "template.html" вместо HTMLstring. Таким образом, я смогу использовать ту же директиву с разными файлами шаблонов в зависимости от того, какой тип popover я хочу показать. Это мой план в любом случае.
Итак, как мне лучше всего загрузить html-код из моего шаблона .html и использовать его вместо HTMLstring в директиве AngularJs ниже?
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: '='
}
};
});
Ответы
Ответ 1
Быстрое решение использует 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
Ответ 2
Чтобы выполнить ответ от 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);
});
}
};