我目前正在学习 AngularJS,我想创建一个通知模块,但我找不到任何帮助教程。
我希望所有通知都添加到一个 div 中,我需要首先创建它。这是我的第一个问题。我必须在哪里将元素附加到 DOM 中,这样代码仍然是有效的 Angular 代码。
<!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'));
}
}]);
为了创建通知,我编写了一个工厂,在 #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 方法完成的示例,但它总是发生在另一个指令或 Controller 内,因为需要作用域,而我在工厂内没有作用域。
我做错了什么?
最佳答案
定义一个 Controller ,它维护一组通知:
notification.controller('NotificationController', function() {
var ctrl = this;
ctrl.notificationArray = [ ];
ctrl.addNote = function (note) {
ctrl.notificationArray.push(ctrl.notificationArray.length + ". " + note);
};
});
然后在 HTML 中,对此数组执行 ng-repeat:
<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>
关于javascript - AngularJS 在工厂中创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33357316/