什么是Angularjs $编译功能,第二个和第三个参数
问题描述:
我有这样的例子
<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)
,它不再工作。
这是为什么?
这是小提琴。
答
的$compile
第三个参数是maxPriority
。从the docs:
仅适用指令低于给定优先级(仅影响根 元素(S),而不是他们的子女)
当你运行它像$compile(element, null,-9999)($scope);
,你告诉编译器跳过所有关于element
的指令优先级大于-9999
。这就是为什么compileTemplate
指令将不会是“自编”因为默认的优先级为0和ngBindHtml
不会运行两次,因为:
该指令的优先级执行0
当拆除第三个参数ngBindHtml
将被编译并重新链接。同样的事情也会发生在你的compileTemplate
指令中。既然你已经设置了$watch
和$compile
被称为它的内部,你会得到
[$rootScope:infdig] 10 $digest() iterations reached. Aborting!
错误,因为无限的“自我编译”的。这是所谓的"Double Compilation"问题之一。
第二个参数是transclude
function(它不会在你的情况,因为它是作为null
通过发挥任何作用):
功能提供给指令 - 弃用。