Answer the question
In order to leave comments, you need to log in
Templates in angularjs?
Hello, please tell me how to do the following:
I receive an array of objects - these are banner templates, each banner has its own layout, and each banner has several products. The layout of the template and products come in the objects, which need to be substituted into the same layout. That is something like this:
var templates: [
{
"layout" : "<div><h1>{{layout name}}</h1><p ng-repeat='item in template.items'>{{item.name}}</p></div>",
"items" : [
{"name" : "item 1"},
{"name" : "item 2"}
]
}
];
Answer the question
In order to leave comments, you need to log in
Sketched on the knee ( DEMO ).
<!DOCTYPE html>
<html data-ng-app="app">
<head>
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script>
window.templates = [
{
"layout" : "<div><h1>{{name}}</h1><p ng-repeat='item in items'>{{item.name}}</p></div>",
"name": "items",
"items" : [
{"name" : "item 1"},
{"name" : "item 2"}
]
}
];
</script>
<script src="script.js"></script>
</head>
<body>
<div data-banner="items"></div>
</body>
</html>
angular.module('app', [])
.config(function($provide) {
$provide.constant('bannerTemplates', window.templates);
})
.directive('banner', function($compile, bannerTemplates) {
return {
// Изолируем scope
scope: {},
link: function(scope, elem, attrs) {
// Ключ баннера
var bannerName = attrs.banner,
banner;
// Находим объект баннера
for (var i = 0, ii = bannerTemplates.length; i < ii; ++i) {
// Сохраняем в переменную
banner = bannerTemplates[i];
// Если нашли - останавливаем цикл
if (banner.name === bannerName) {
break;
}
}
// Добавляем данные в scope
angular.extend(scope, banner);
// Компилируем шаблон, получаем jQuery/jqLite объект
var html = $compile(banner.layout)(scope);
// Вставляем в контейнер
elem.append(html);
}
};
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question