W
W
WebDev2015-04-30 11:51:00
Angular
WebDev, 2015-04-30 11:51:00

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"}
     ]
  }
];

How to make angular directives work in layout?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2015-04-30
@kirill-93

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);
    }
  };
});

K
Kano, 2015-04-30
@Kano

Here is a more general solution to simply include a template from scope plnkr.co/edit/MJlwYcJr6WFiULXP5SrX?p=preview

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question