什么是 Angularjs $compile函数 2nd 和 3rd 参数



我有这个例子

<div ng-controller="MyCtrl">
<div compile-template ng-bind-html="post"></div>
</div>

和 angularjs 代码:

angular.module('myApp',[])
.controller('MyCtrl', function($scope, $sce,$timeout) {
$scope.name = 'World';
$scope.post = $sce.trustAsHtml("<h1>hello {{name}}</h1>");
$timeout(function(){
$scope.name = "3333";
},3000);
});
angular.module("myApp").directive('compileTemplate', ["$compile", "$parse", function($compile, $parse) {
return {
restrict: 'A',
link: function($scope, element, attr) {
var parse = $parse(attr.ngBindHtml);
function value() { return (parse($scope) || '').toString(); }
$scope.$watch(value, function() {
$compile(element, null,-9999)($scope); 
});
}
}
}]);      

如果你仔细观察,你会注意到这个功能。

$compile(element, null,-9999)($scope);

如果我把它$compile(element)($scope),它不再工作了。

为什么?

这是小提琴。

http://jsfiddle.net/bugd67e3/4/

$compile的第三个参数是maxPriority。从文档中:

应用低于给定优先级的指令(仅影响根目录 元素,而不是其子元素(

当你像$compile(element, null,-9999)($scope);一样运行它时,你告诉编译器跳过优先级大于-9999element上的所有指令。这就是为什么compileTemplate指令不会"自编译"的原因,因为默认优先级为 0 并且ngBindHtml不会运行两次,因为:

此指令在优先级级别 0 执行。

删除第三个参数时,ngBindHtml将被编译并再次链接。同样的事情也会发生在你的compileTemplate指令上。由于您已经设置了一个$watch并且$compile在其中调用,因此您将获得

[$rootScope:infdig] 10 $digest() iterations reached. Aborting!

由于无限的"自我编译"而出错。这是所谓的"双重编译"问题之一。

第二个参数是transclude函数(它在您的情况下没有任何作用,因为它是作为null传递的(:

指令可用的函数 - 已弃用。

相关内容

最新更新