2015-10-26 69 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)。 –