2014-01-24 26 views
0

我正在創建一個Angular服務,該服務將向DOM添加一個簡單的通知框並顯示它,而不必添加HTML代碼並寫入在必要時隱藏和顯示的邏輯。在文檔已被加載後將角度指令附加到DOM不適用於ngAnimate

該服務被稱爲$通知,並如下使用:

$notify.error("this is an error", {position: "bottom-left"}); 

的服務將使用angular.element打造的通知框,並把它添加到DOM。所有這些都很好。不過,我也在使用ngAnimate和animate.css讓通知在播放時平滑地滑動並在關閉時滑出。我已經驗證過,如果我只是將通知HTML代碼粘貼到我的頁面中,則動畫工作,但在通過服務動態添加代碼時不起作用。文件加載時項目是否必須位於DOM中以便ngAnimate正常工作?我已驗證Angular服務已加載並正確插入HTML代碼,但未應用任何動畫。這是HTML和CSS的樣子。

HTML:

<div class="simple-notify simple-notify-top-left simple-notify-info" ng-if="toggle"> 
    <simple-notify-header>Hello!<span class='simple-notify-dismiss pull-right' ng-click='doSomething()'>&times;</span></simple-notify-header> 
    <simple-notify-body>Some bogus text here!</simple-notify-body> 
</div> 

CSS/LESS:

.simple-notify { 
    &.ng-enter { 
     display:none; 
     animation: @animate-enter @animation-length; 
     -webkit-animation: @animate-enter @animation-length; 
    } 
    &.ng-enter-active { 
     display:block; 
    } 
    &.ng-leave { 
     animation: @animate-leave @animation-length; 
     -webkit-animation: @animate-leave @animation-length; 
    } 
} 

謝謝!

回答

0

您不應該從服務修改頁面上的元素,這是指令的用途。你應該在你的HTML元素和那個地方創建一個屬性指令。您可以在您的指令中使用$notify服務中的$rootScope.$broadcast$scope.$on。或者,您可以完全取消$notify服務,只使用$rootScope.$broadcast,因爲它可以接受任意數量的參數。

最後,您需要使用$compile服務,以便在您將HTML添加到正文後正確運行HTML。 $compile是將原始DOM轉換爲Angular將要處理的代碼。

從鏈接函數中你的指令的scope.$on處理程序中,你會有類似的東西。 $compile('<div>template code here</div>')(scope, function(cloned, scope){ element.append(cloned); });

但是你也需要清理。您可以將代碼添加一次作爲指令的模板,並使用不同的內容來顯示/隱藏它,而不是添加/刪除DOM。