【问题标题】:Appending angular directives to the DOM after document is already loaded doesn't work with ngAnimate在文档已经加载后向 DOM 附加角度指令不适用于 ngAnimate
【发布时间】:2014-01-25 07:04:12
【问题描述】:

我正在创建一个 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/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;
    }
}

谢谢!!!

【问题讨论】:

    标签: javascript jquery html css angularjs


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      相关资源
      最近更新 更多