Javascript AngularJS在工厂中创建元素

Javascript AngularJS在工厂中创建元素,javascript,html,angularjs,Javascript,Html,Angularjs,我目前正在学习AngularJS,我想创建一个通知模块,但我找不到任何帮助教程 我希望我的所有通知都添加到一个div中,我首先需要创建一个div。所以我的第一个问题来了。我必须在何处将元素附加到DOM中,以便代码仍然有效 <!DOCTYPE html> <html> <head> ... </head> <body> ... <div class="notif

我目前正在学习AngularJS,我想创建一个通知模块,但我找不到任何帮助教程

我希望我的所有通知都添加到一个div中,我首先需要创建一个div。所以我的第一个问题来了。我必须在何处将元素附加到DOM中,以便代码仍然有效

<!DOCTYPE html>
<html>
    <head>
        ...
    </head>
    <body>
        ...
        <div class="notification-center"> //Element I need to create
            ... //Notifications come here
        </div>
    </body>
</html>

...
...
//我需要创建的元素
... //通知到这里来
我通过在module.run()函数中添加div解决了这个问题,但不知何故,我认为它不应该存在

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'));
    }
}]);
var notification=angular.module('notification',[]);
notification.run([function()){
var el=角度元素(“#通知中心”);
if(!角度元素(el).长度){
el=angular.element(“”).attr('id','notificationcenter').text('{{text}}').appendTo(angular.element('body'));
}
}]);
为了创建通知,我编写了一个工厂,将另一个div附加到#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'));
    };
}]);
notification.factory('notification',[function()){
var默认值={
持续时间:5000
};
返回功能(文本、设置){
var element=angular.element(“”).addClass('notification').text(text).appendTo(angular.element('notificationcenter'));
};
}]);
基本上,这也是可行的,但是当我想要为通知创建一个指令时,它将不适用。我看到过使用$compile方法完成的例子,但它总是发生在另一个指令或控制器中,因为需要一个作用域,而我在工厂中没有


我做错了什么?

定义一个控制器,它维护一系列通知:

  notification.controller('NotificationController', function() {
      var ctrl = this;
      ctrl.notificationArray = [ ];
      ctrl.addNote = function (note) {
          ctrl.notificationArray.push(ctrl.notificationArray.length + ". " + note);
      };
  });
然后在HTML中,在此数组上执行ng重复:

    <div ng-controller="NotificationController as ctrl">
        <div class="notification-center" ng-if="ctrl.notificationArray.length>0">
            <div class="notification" ng-repeat="note in ctrl.notificationArray">
               {{note}}
            </div>
        </div>
        <button ng-click="ctrl.addNote('another note');">Add note</button>
    </div>

{{note}}
添加注释

使用
angular.element
与使用JQuery没有什么不同。如果您计划制作一个操作DOM的指令,它应该使用一个模板,而不是
angular.element
。工厂永远不应该对DOM代码负责。这是个好主意,但是我必须在哪里附加“包装器”-div?在module.run()函数中?因为我想重用模块,并且我不想关心手动将div写入模板以使其可重用,所以您应该创建一个“指令”。请按照AngularJS教程学习如何操作(docs.AngularJS.org/guide/directive)。