0

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.

2
  • admin-item in items.html? you do not have that directive i guess Commented Jan 30, 2015 at 2:05
  • 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 Commented Jan 30, 2015 at 9:59

1 Answer 1

0
+100

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Leg! - thank you kindly. a little switch-a-roo on implementation and all is calm once more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.