调用没有元素的角度指令

calling angular directive without element

本文关键字:指令 元素 调用      更新时间:2023-09-26

我正在尝试在 angular 中构建通知服务,而无需在代码中添加随机元素。大多数通知存储库都需要在代码中添加一个元素来调用指令:

HTML
<div notifications></div>
DIRECTIVE
myApp.directive('notifications', function() {});

似乎此代码存在的唯一原因是需要调用指令。调用通知时,可以在提供程序中处理所有"设置":

$notify(settings)

此外,如果可以在没有元素的情况下调用指令,那么指令如何在主体底部创建一个"通知"元素,并将自身绑定到它?

所以我问,是否可以在没有这种任意代码的情况下调用指令?或者有更简单的方法可以做到这一点? 还是这是一个愚蠢的问题?

提前致谢:)

我建议不要使用以下代码,至少对于常见做法而言。此通知指令是一种边缘情况,其中只有一个指令会被放在页面上,它可以存在于根范围之外的隔离作用域中,因为我希望它的数据顶部是从服务填充的。

我只是在表明所问的是可能的。应避免使用$compile,并且有更好的方法,例如要求将元素添加到 DOM 中,以便可以控制通知指令绑定到的元素和范围。

module.directive('notification', 'blahBlahBlah');
module.run(function($document, $compile, $rootScope) {
    // create an isolated scope so that the notification directive does not have an option to pollute the root scope.
    var isolatedScope = $rootScope.$new(true);
    var notificationDir = '<div notification></div>';
    var bodyElem = angular.element($document[0].body);
    bodyElem.append(notificationDir)
    $compile(notificationDir )(isolatedScope );
});