0
votes

I am generating a nested list using angular directives with model a structure like:

{
  items: [{
    type: "section",
    name: "Section 1",
    items: [{
      type: "section",
      name: "Section 1-1",
      items: [{
        type: "product",
        name: "Bag",
        sku:"xyz"
      }, {
        type: "article",
        name: "Polo"
      }, {
        type: "product",
        name: "T-Shirt",
        sku:"abt"
      }]
    }, {
      type: "section",
      name: "Section 1-2",
      items: [{
        type: "product",
        name: "Bat",
        sku:"x4ty"
      }, {
        type: "article",
        name: "Golf"
      }, {
        type: "info",
        name: "Map"
      } ,{
        type: "product",
        name: "Racket",
        sku:"jkg56"
      }]
    }]
  }, {
    type: "section",
    name: "Section 2",
    items: [{
      type: "section",
      name: "Section 2-1",
      items: [{
        type: "article",
        name: "Headline"
      }, {
        type: "article",
        name: "Sport"
      }]
    }]
  }]
}

What I would like to achieve is to build this tree dynamically based on the type of the item.

Here is a plunker of what I'm trying to do (it's not working!!).

plunker demo

The idea being I'd like to be able to add new types of item (currently product and article but I'm sure more will arise).

I'm currently trying to trigger the directive on the class attribute as demonstrated in the items.html template - this clearly don't work.

Bottom line - I'd like to either load a separate directive based on the type attribute of the current scope model or dynamically select template and link function.

1
admin-item in items.html? you do not have that directive i guess - PSL
No - i was hoping to just use the class name to trigger directive and used restrict: "C". Feel free to suggest improvements - I'm not precious about things :P - Ian Wood

1 Answers

0
votes

You can do this with $compile.

app
  .directive('adminItem', function($compile){
    return {
      restrict: "A",
      replace: true,
      template: "<div></div>",
      scope: {
        item: '=adminItem'
      },
      link: function(scope, element, attrs, ctrl) {
        element.append($compile('<div admin-' + scope.item.type +'="item"></div>')(scope));
      }
    };
  })

Here is the updated plnkr.

It's not perfect, but it get's the idea across. I used attribute directives, but it'll work with any type.