2014-01-24 88 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。