gpt4 book ai didi

javascript - 在文档加载后将 Angular Directive(指令)附加到 DOM 不适用于 ngAnimate

转载 作者:行者123 更新时间:2023-11-28 11:26:02 26 4
gpt4 key购买 nike

我正在努力创建一个 Angular 服务,它将一个简单的通知框附加到 DOM 并显示它,而无需添加 HTML 代码并编写逻辑来在必要时隐藏和显示它。

该服务名为 $notify,使用如下:

$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/更少:

.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;
}
}

谢谢!!!

最佳答案

您永远不应该从服务修改页面上的元素,这就是指令的用途。您应该在 body 上创建一个属性指令HTML 元素和您的逻辑所在的位置。您可以使用 $rootScope.$broadcast来自你的 $notify服务与$scope.$on在你的指令中。或者,您可以废弃 $notify完全服务,只需使用 $rootScope.$broadcast因为它可以接受任意数量的参数。

最后,您需要使用 $compile服务使您的 HTML 在您将其添加到正文后正常运行。 $compile是将原始 DOM 转换为 Angular 将处理的代码的原因。

从指令的 scope.$on 内部链接函数中的处理程序,你会有类似的东西。 $compile('<div>template code here</div>')(scope, function(cloned, scope){
element.append(cloned);
});

但是您还需要进行清理。您可能只添加一次代码作为指令的模板,并使用不同的内容显示/隐藏它,而不是添加/删除 DOM。

关于javascript - 在文档加载后将 Angular Directive(指令)附加到 DOM 不适用于 ngAnimate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21342958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com