我正在尝试以 Angular 构建通知服务,而不必在代码中添加随机元素。大多数通知存储库都需要在代码中添加一个元素来调用指令:
HTML
<div notifications></div>
DIRECTIVE
myApp.directive('notifications', function() {});
这段代码存在的唯一原因似乎是需要调用指令。当调用通知时,所有“设置”都可以在提供程序中处理:
$notify(settings)
此外,如果可以在没有元素的情况下调用指令,那么指令如何在主体底部创建“通知”元素并将其自身绑定(bind)到它?
所以我问,是否可以在没有这段任意代码的情况下调用指令?还是有更简单的方法来做到这一点?或者这是一个愚蠢的问题?
提前致谢:)
最佳答案
我建议反对使用下面的代码,至少对于常见做法是这样。 此通知指令是一种边缘情况,其中只有一个指令会被放置在页面上,并且它可以存在于根范围之外的隔离范围中,因为我希望它的数据顶部从服务中填充。
我只是想表明所问的问题是是可能的。 应避免使用 $compile,并且有更好的方法,例如要求将元素添加到 DOM 中,以便可以控制通知指令绑定(bind)的元素和范围。
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 );
});
关于javascript - 调用不带元素的 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27119731/