2015-10-26 66 views
0

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

我想我所有的通知添加到一个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()函数内的股利,但不知何故,我不认为它应该是有

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')); 
    } 
}]); 

要创建我写了一个通知工厂,我追加#notificationcenter div内的另一个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')); 
    }; 
}]); 

基本上这也适用,但是当我想为通知创建一个指令时,它不适用。我已经看到了使用$ compile方法完成的示例,但它总是在另一个指令或控制器内部发生,因为需要一个范围,而这在工厂内并不存在。

我在做什么错?

+2

https://docs.angularjs.org/guide/directive – Phil

+1

使用'angular.element'与使用JQuery没有区别。如果你打算制作一个操作DOM的指令,它应该使用一个模板,而不是'angular.element'。而工厂应该从不**对DOM代码负责。 – Claies

回答

2

定义的控制器,它保持通知的阵列:在HTML

notification.controller('NotificationController', function() { 
     var ctrl = this; 
     ctrl.notificationArray = [ ]; 
     ctrl.addNote = function (note) { 
      ctrl.notificationArray.push(ctrl.notificationArray.length + ". " + note); 
     }; 
    }); 

然后,此阵列上执行的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> 
+0

这是一个好主意,但我要在哪里追加“包装”-div?在module.run()函数里面?因为我想重复使用模块,而且我不想在模板中手动编写div –

+0

要使这个模块可重用,您应该创建一个“指令”。请遵循AngularJS教程来学习如何做到这一点(docs.angularjs.org/guide/directive)。 –