2017-08-15 67 views
2

我有這樣的例子

<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/

回答

2

$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通過發揮任何作用):

功能提供給指令 - 棄用。

相關問題