【问题标题】:angular directive based on model property基于模型属性的角度指令
【发布时间】:2015-01-30 01:55:36
【问题描述】:

我使用角度指令生成嵌套列表,模型结构如下:

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

我想要实现的是根据项目的类型动态构建这棵树。

这是我正在尝试做的事情(它不起作用!!)。

plunker demo

我希望能够添加新类型的项目(目前是产品和文章,但我相信会出现更多)。

我目前正在尝试触发类属性上的指令,如 items.html 模板中所示 - 这显然不起作用。

底线 - 我想根据当前作用域模型的 type 属性加载单独的指令,或者动态选择模板和链接函数。

【问题讨论】:

  • admin-item 在 items.html 中?我猜你没有那个指令
  • 不 - 我希望只使用类名来触发指令并使用限制:“C”。随意提出改进建议-我对事物并不珍贵:P

标签: angularjs angularjs-directive


【解决方案1】:

你可以用 $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));
      }
    };
  })

这是更新后的plnkr

它并不完美,但它让想法得到了体现。我使用了属性指令,但它适用于任何类型。

【讨论】:

  • 腿! - 非常感谢你。在实施过程中稍作切换,一切又恢复了平静。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-27
  • 2015-03-03
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
相关资源
最近更新 更多