AngularJS - 动态创建指定指令的元素 [英] AngularJS - Dynamically creating elements that specify directives

查看:29
本文介绍了AngularJS - 动态创建指定指令的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的设置:

  • Controller c 广播事件 e
  • 指令 d 侦听 e,并在 e 上通过 append 写入 DOM,在此过程中,创建指定的新元素指令 d2.

IE: element.append('<directiveTwo ...>')

  • 指令 two 永远不会被 Angular 调用
  • 当我检查 DOM(和调试)时,我看到控制器 c 和指令 d 正在执行它们的工作,并且我有新的 directiveTwo 元素.

缺少什么?动态创建这些元素后,需要做什么来触发指令 2 调用?

解决方案

参见 $compile.您可以像这样使用此服务:

var newDirective = angular.element('

');element.append(newDirective);$compile(newDirective)($scope);

这将执行新元素的编译和链接,并将 d2 设置为操作.

但是,如果您能以某种方式根据其他内置指令(如 ng-repeatng-include)重写原始指令,您可能会发现它更简单、更有棱角将为您执行编译和链接.

如果你的指令足够简单,它可以在听到你的事件时做一些类似于添加到数组的事情,并指定一个模板

<div d2="evt"></div>

I have a setup like this:

  • Controller c broadcasts event e
  • Directive d listens for e, and on e, writes to the DOM via append, and in so doing, creates new elements specifying a directive d2.

IE: element.append('<directiveTwo ...>')

  • Directive two is never called by Angular
  • When I inspect the DOM (and debug) I see that Controller c and directive d are doing their jobs, and I have new directiveTwo elements.

What is missing? What needs to be done to trigger the directive 2 call after dynamically creating those elements?

解决方案

See $compile. You can use this service similarly to this:

var newDirective = angular.element('<div d2></div>');
element.append(newDirective);
$compile(newDirective)($scope);

This will perform the compilation and linking of your new element, and set d2 into action.

However you may find it simpler and more angular if you can somehow rewrite your original directive in terms of other built in directives like ng-repeat or ng-include that will perform the compile and link for you.

If your directive is simple enough it could just do something along the lines of adding to an array when hearing your event, and specify a template like

<div ng-repeat="evt in recordedEvents">
    <div d2="evt"></div>
</div>

这篇关于AngularJS - 动态创建指定指令的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆