directive()的第二个参数,传入$compile参数的情况
angular.module('name1').directive('directiveName', function($compile) {
return{
restrict: 'E',
scope: {},
link:function(scope,element,attrs){
//一些DOM操作
$compile(element.contents())(scope.$parent); //疑点
}
}
}
疑点:$compile()()的作用及用法
希望大家能帮帮忙
这个先百度下吧,complile应该是预编译
你可以这么简单的理解为:
$compile() 可以将普通的结构编译成angular认识的结构。 比如你的DOM片段里面写的ng-xx 或者angular的 {{ value }}等等。你如果不进行编译,这些DOM节点直接插入DOM树中,Angular是无法识别的。
后面的()中一般我在使用时传入的是需要给编译这段代码作用的SCOPE对象。一般我会从当前作用域 $new()一个出来。
一般我这么用,比如如下代码(某个指令里的一部分)
var myScope = scope.$new();
myScope.showThis = true;
var temp = $compile('<div ng-show="showThis">TEXT</div>')(myScope);
temp.appendTo('body');
参考:
$compile官方文档
Compile的细节
作用其实就是:
Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
你提问里的用法其实就是ng提供的一种动态编译方法,实际就是起到了上述的作用。