如何动态操作角度ng-include命令

时间:2016-03-05 18:11:08

标签: javascript angularjs angularjs-ng-include

是否可以动态地将ng-include元素添加到HTML页面并对其进行操作?

我有一个Drag N Drop应用程序,您可以将元素拖到页面上,在放置区域中,元素将替换为更详细的元素。例如,您拖动一个显示日历的框,当它被删除时,会显示一个日历。为了清楚起见,创建了一个新元素并将其添加到DOM中,它在删除之前不存在。

当元素被删除时,我希望我可以用一大块HTML替换它,如下所示。而不是在字符串中定义标记,就像它现在不是很好:

<div class='panel panel-default'>
  <div class='panel-heading'>
    <h3 class='panel-title'>
      <span class='glyphicon glyphicon-remove'></span>
      WIDGET NAME
      <spanclass='glyphicon glyphicon-cog'></span>
    </h3>
  </div>
  <div class='widgetContainer' ng-include="'widgets/widget.html'"></div>
</div>

当上述HTML插入页面时,不包括引用的HTML文件。

我想要发生的是加载的HTML文件,其中包含小部件标记并包含在适当的位置。

我是Angular的新手,所以我不知道这是因为:

  • 动态添加ng-include isn #t;不支持
  • 我是否需要对控制器做些什么来处理这个逻辑
  • 我应该使用标签而不是属性吗?
  • 它是不可能的。

请提供解决方案示例,正如我所说,我是Angular的新手。

由于

更新

用于创建我想要动态添加到页面的HTML的代码如下所示

$("#template").append(
    " \
    <div class='panel panel-default'>\
    <div class='panel-heading'>\
    <h3 class='panel-title'>\
    <span style='padding-right: 10px; cursor:pointer;' class='glyphicon glyphicon-remove' onclick='removeElement(this)'></span>\
    " + widgetDetail['serviceName'] + "\
    <span style='float:right; cursor:pointer;' class='glyphicon glyphicon-cog' onclick='toggleWidgetDetail(this)'></span>\
    </h3>\
    </div>\
    <div class='markupContainer' ng-include=\"'widgets/" + id +".html'\"></div>\
    </div>\
    "
);

我已将完整的代码上传到GitHub。目前HTML5 javascript正在处理拖放方面,可以在文件/public/javascripts/js_dragndrop.js中看到。添加到页面中的新窗口小部件(上面的代码)位于/public/javascripts/jq_dragndrop.js

我正处于原型设计阶段,尝试制定DragNDrop元素,因此不要期望高质量的代码:)

1 个答案:

答案 0 :(得分:0)

我找到了一种方法,通过将HTML5 drop and drop代码移动到AngularJS指令中然后(使用这个[Compile dynamic template from outside of angular]作为指南)来实现我想要的东西。将html模板加载到我想要的地方。

主要代码更改如下所示:

angular.element(document).injector().invoke(function ($compile) {

  var widgetDetail = widgets[e.dataTransfer.getData('Text')];

  var obj = $("#template");
  var scope = obj.scope();

  obj.append(
    "<div class='panel panel-default'><div class='panel-heading'><h3 class='panel-title'>\
     <span style='padding-right: 10px; cursor:pointer;' class='glyphicon glyphicon-remove' onclick='removeWidget(this)'></span>\
     " + widgetDetail['serviceName'] + "\
     <span style='float:right; cursor:pointer;' class='glyphicon glyphicon-cog' onclick='toggleWidgetDetail(this)'></span>\
     </h3></div><div class='markupContainer' ng-include=\"'widgets/" + widgetDetail['serviceId'] + ".html'\"></div>\
     "
   );

   $compile(obj.contents())(scope);
   scope.$digest();
});

如果您有兴趣,可以在Git Project /public/controllers/template.js 中找到完整的代码。