I'm currently learning AngularJS and I want to create an module for notifications, but I can't find any helping tutorials.
I want all my notifications add into a div, which I need to create at first. So here comes my first question. Where do I have to append the element into the DOM so the code is still valid angular-code.
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
<div class="notification-center"> //Element I need to create
... //Notifications come here
</div>
</body>
</html>
I solved it by appending the div inside the module.run() function, but somehow I don't think it should be there
var notification = angular.module('notification', []);
notification.run([function(){
var el = angular.element('#notificationcenter');
if(!angular.element(el).length){
el = angular.element('<div>').attr('id', 'notificationcenter').text('{{ text }}').appendTo(angular.element('body'));
}
}]);
For creating the notifications I've written an factory where i append the another div inside the #notificationcenter div.
notification.factory('notification', [function(){
var defaults = {
duration: 5000
};
return function(text, settings){
var element = angular.element('<div>').addClass('notification').text(text).appendTo(angular.element('#notificationcenter'));
};
}]);
Basically this works aswell, but when I want to create a directive for the notification, it won't apply. I've seen examples where it's done with the $compile method, but it always happened inside another directive or controller as an scope is needed, which I don't have inside a factory.
What am I doing wrong?
angular.elementis no different from using JQuery. if you are planning on making a directive that manipulates the DOM, it should use a template, notangular.element. and factories should never be responsible for DOM code.