[英]Dynamically adding directive to element in Angular
I have a directive called "resizable" that adds functionality to an element to make it resizable. 我有一个称为“可调整大小”的指令,该指令可向元素添加功能以使其可调整大小。
I want to conditionally apply this directive to an element from a controller. 我想有条件地将此指令应用于控制器中的元素。
When I add this directive at run-time using attr
, the attribute for the "resizable" directive is added, but the directive doesn't execute. 当我在运行时使用attr
添加此指令时,将添加“可调整大小”指令的属性,但该指令不会执行。
Here's an illustration: http://jsfiddle.net/HB7LU/3995/ 这是一个例子: http : //jsfiddle.net/HB7LU/3995/
What I'm expecting is that when $('span').attr('resizable', '');
我期望的是当$('span').attr('resizable', '');
is called, the class funky
should be added to the span
. 调用时,应该将funky
类添加到span
。 Why doesn't it? 为什么不呢?
You need to use the $compile
directive to notify angular of the changes. 您需要使用$compile
指令将更改通知角度。 Basically the logic goes like this: "I've changed something within my element that you should be concerned about. Please compile the DOM against my scope": 基本上,逻辑是这样的:“我已经更改了您应该关注的元素内的某些内容。请针对我的范围编译DOM”:
function Controller($scope, $compile) {
// Apply resizable directive to span
var span = $('span');
span.attr('resizable', '');
$compile(span)($scope);
}
NOTE: You SHOULD NOT use jQuery natively within a controller (... or anywhere really). 注意:您不应该在控制器(...或其他任何地方)中本机使用jQuery。 It may select span
tags outside of your element of interest. 它可能会在您感兴趣的元素之外选择span
标签。 You SHOULD try writing a directive to wrap the logic that applies your resizable directive. 您应该尝试编写指令以包装应用可调整大小指令的逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.