2

嗨我想知道, 如果有一種方法可以在$ scope中獲得類似promise(我猜這將是postLink)。 我一個懸而未決的問題在這裏:AngularJS: how to know when the $compile has finished?這是非常相似,我的問題,

,但我不知道是否有人能幫助我明白我怎麼能勾postLink事件:

我有以下代碼:

var compiledEl = 
$compile("<link data-ng-repeat='stylesheet in injectedStylesheets' data-ng-href='{{stylesheet.href}}' rel='stylesheet' />"); 
head.append(compiledEl(scope)); 

所以我不知道在哪裏添加promise.resolved(true); 因爲我看不到後鏈接。我怎麼知道$ compile何時結束。 感謝

回答

3

你可以讓自己的指令:

app.directive('compileCallback',function(){ 
    return { 
    priority: 1001, // make sure it's the last to run 
    link: function (scope, element, attrs){ 
     scope.$eval(attrs.compileCallback); 
    } 
    } 
}); 

內模板:

<link data-ng-repeat='stylesheet in injectedStylesheets' data-ng-href='{{stylesheet.href}}' rel='stylesheet' compile-callback="promiseResolve()" /> 
+2

這是一個很好的答案,但是 - 你可能不希望創建這個指令一個孤立的範圍,因爲那麼你強制這個指令是唯一一個具有隔離範圍的特定html標籤。更好的實現將使用attrs.compileCallback來實現相同的行爲。 –

+0

@OferSegev謝謝 –

0

基於角文檔,它說:

Directives with greater numerical priority are compiled first.

所以,我不認爲設置這個優先這裏的價值是正確的,意圖是它會最後運行。如果我錯了,請糾正我。

儘管此指令將在完成時調用該函數。

而且,我把一個檢查,以確保compileCallback設置,如:

if (angular.isFunction(scope.compileCallback)) { 
    scope.compileCallback(); 
}